Spring整合MyBatis

本文详细介绍了如何在Spring框架下整合MyBatis,包括配置数据源、SqlSessionFactory、Mapper扫描器,以及编写和测试EmployeeMapper接口中的getOne方法,用于根据ID从数据库中获取对象。
摘要由CSDN通过智能技术生成

资源下载链接

Spring整合MyBatis

一、需求分析

        掌握Spring整合MyBatis,实现从数据库中根据id查找对象的功能

二、编码实现

1、数据库环境

        mybatis数据库,t_employee表,3条记录

2、新建项目

        引入pom.xml文件,导入applicationContext.xml、db.properties、log4j.properties

3、数据封装类

        com.sw.pojo包,Employee类

@Data
public class Employee {
    private int id;
    private String name;
    private int age;
    private String position;
}
4、mapper层

        com.sw.mapper包,EmployeeMapper接口

public interface EmployeeMapper {
    Employee getOne(int id);
}

        com/sw/mapper目录,EmployeeMapper.xml文件

<mapper namespace="com.sw.mapper.EmployeeMapper">
    <select id="getOne" parameterType="int" resultType="com.sw.pojo.Employee">
        select * from t_employee where id = #{id}
    </select>
</mapper>
5、配置Spring

        resources目录,applicationContext.xml

        1)配置数据源
    <!--引入属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${mysql.driver}"/>
        <property name="url" value="${mysql.url}"/>
        <property name="username" value="${mysql.username}"/>
        <property name="password" value="${mysql.password}"/>
    </bean>
        2)配置SqlSessionFactory
    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--加载MyBatis配置文件-->
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
    </bean>
        3)配置Mapper扫描器
    <!--配置Mapper扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定要扫描的mapper的包-->
        <property name="basePackage" value="com.sw.mapper"/>
    </bean>
        4)配置Spring IOC容器的注解扫描
    <!--配置Spring IOC容器的注解扫描-->
    <context:component-scan base-package="com.sw"/>
6、测试

        com.sw.mapper包,EmployeeMapper类的getOne方法,右键→Generate→Test

    private EmployeeMapper employeeMapper;
​
    @Before
    public void setUp() throws Exception {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        employeeMapper = applicationContext.getBean("employeeMapper", EmployeeMapper.class);
    }
​
    @Test
    public void getOne() {
        Employee one = employeeMapper.getOne(1);
        System.out.println(one);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇 士 Teacher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值