Spring整合Mybatis
1.导包
spring的包 mybtais的包 他们两个结合的包
2.搭建核心配置文件
3.开始整合 mybatis 原始整合
Mapper整合
不管哪种方式都要依赖于sqlSessionFactory
sqlSessionFactory需要依赖于读取mybatis核心配置文件的信息
分为三层:
1.别名设置
<typeAliases>
<package name="cn.hd.entiy"></package>
</typeAliases>
2.数据库的链接信息(可以使用数据库连接池来取代)
<context:property-placeholder location="classpath:resources/db.properties"></context:property-placeholder>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
3.读取映射文件
<bean name="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="cn.hd.mapper.UserMapper"></property>
</bean>
Mapper开发
spring配置bean------------>MaoooferFactoryBean类(需要起名字)
依赖两个
1.sqlSessionFactory 和两个接口的位置
直接写测试代码@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:resources/spring/applicationContext.xml")
public class demo {
@Resource(name = "userDao")
private UserDao userDao;
@Test
public void fun(){
User userById = userDao.findUserById(1);
System.out.println(userById);}
第二种:
这样方式也要写多个mapper mybatis 提供的升级版
配置一个扫描类,自动扫描某个位置下所有的mapper 并起名为对应的小写
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.hd.mapper"></property> </bean>
直接测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:resources/spring/applicationContext.xml")
public class demo {
@Resource(name = "userDao")
private UserDao userDao;
@Test
public void fun(){
User userById = userDao.findUserById(1);
System.out.println(userById);}
@Resource(name = "userMapper")
private UserMapper userMapper;
@Test
public void fun1(){
User userById = userMapper.findUserById(2);
System.out.println(userById);}