整合的目的:首先为什么要用spring,因为spring可以简化Java的开发,ioc容器将对象之间变得松耦合,对象与对象之间不再互相依赖,而是由bean容器来管理他们的生存周期;aop将周边功能与核心业务分离开来,减少了代码冗余,提高了代码的重用性,灵活性;dao利用templet将复杂的数据库连接变得模板化使用起来更加简洁方便,还提供了对事务的支持,并且能够集成ORM框架;springmvc利用servlet分发将逻辑与实现分离;用mybatis的目的是,如果用jdbc templet,这样更接近底层,更有利于sql调优,为啥没人用,因为orm框架更把jdbc进行封装使得与数据库的交互更符合oo思想,更符合Java开发人员的规范。
把mybatis和spring进行整合就是:由本来的Mybatis尽心管理,交由Spring来进行了。
applicationContext.xml:(把之前mybatis的配置文件写入spring来管理)
<?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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启注解扫描 -->
<context:annotation-config />
<!-- 加载数据库配置文件 -->
<context:property-placeholder file-encoding="utf-8" location="db.properties"/>
<!-- 连接数据库的bean -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}"/>
<property name="username" value="${db.uname}"/>
<property name="password" value="${db.pwd}"/>
</bean>
<!-- 会话工厂 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--属性1: 添加别名 -->
<property name="typeAliasesPackage" value="cn.com.how.pojo" />
<!--属性2:注入数据库连接对象 -->
<property name="dataSource" ref="dataSource"/>
<!--属性3:pojo类的xml的配置文件 -->
<property name="mapperLocations" value="classpath:cn/com/how/mapper/*.xml"/>
</bean>
<!-- 扫描mapper类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.com.how.mapper"/>
</bean>
</beans>
测试类:
@RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入, spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境。
@ContextConfiguration:引入配置文件,多个可以用逗号隔开
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpring_Mybatis {
@Autowired
UserMapper userMapper;
@Test
public void test_queryAllUser() {
List<User> ulist = userMapper.queryAllUser();
for(User u :ulist) {
System.out.println(u);
}
}
}