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);
}