十二·整合mybatis
1:导入相关jar包
12.1·回忆Mybatis
public class User {
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
}
12.2 MyBatis-Spring
1.编写数据原配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 druid
我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
2.sqlSessionFactory
<!-- sqkSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<!-- 绑定mybatis配置文件 -->
<property name="configLocation" value="classpath:mabits-config.xml"></property>
<property name="mapperLocations" value="classpath:com/ityuan/mapper/*.xml"></property>
</bean>
3.sqlSessionTemplate
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能使用构造器注入sqlsessionFactory 因为他没有set方法 -->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
4.需要给接口加上实现类
public class UserMapperImpl implements UserMapper {
// 我们的所有操作,都使用sqlSession来执行,在原来,现在都使用SqlSessionTemplate;
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
5.将自己的实现类注入到Spring中
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能使用构造器注入sqlsessionFactory 因为他没有set方法 -->
<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
</bean>
6.测试使用即可
public class MyTest {
@Test
public void test1() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper");
for(User users:userMapper.selectUser()){
System.out.println(users);
}
}
}