我的spring整合mybatis笔记

Spring整合mybatis

用法

1.导入依赖:spring-webmvc、spring-jdbc、aspectjweaver、mybatis-spring

2.以前我们使用mybatis-config.xml;现在数据、sqlsesion交给spring-dao.xml;

mybatis-config.cml----用作配置别名、settings等
applicationContext.xml----用作配置spring入口,通常放bean对象以及resources下其他xml文件( < import resource=“xx.xml”/> )
spring-dao.xml—底层数据库连接【数据源、sqlSessionFactory、sqlSessionTemplate(即sqlSession 注意这里使用构造器注入方式)】

3.以前的mappers注册,现在我们使用xxMapperImpl.java实现xxxMapper.java
这样我们就可以不用去核心配置文件里绑定mapper
(即写一个接口实现类)

我们也可以在xxxMapperImpl类里return sqlSession.getMapper(接口类.class).接口里方法 的方式来避免测试里使用sqlSession

4.测试:

ApplicationContext context=new ClassPathXMLApplicationContext("applicationContext.xml");//获取到配置
UserMapper userMapper=context.getBean("userMapper",UserMapper.class);//得到我们需要的Mapper对象

总结改变:

1.不需要写mybatis工具类了,sqlSession也放在了spring-dao.xml里了

2.新增了一个mapperImpl文件不再需要绑定,

3.核心配置文件部分功能在spring-dao.xml里写了

4.我们最后获取applicationContext.xml

补充:

方法二:

1.xxxMapperImpl类继承SqlSessionDaoSupport 实现接口

下面就可以直接得到sqlSession

SqlSession sqlSession=getSqlSesssion();
retrun sqlSession.getMapper(接口.class).接口方法();//就可以得到接口

2.这里我们就可以省略spring-dao.xml里sqlSession注入

3.applicationContext.xm里还需要添加sqlSessionFactory对象注入

<bean id="userMapper2" class="xx.xxx.xx.xx.xxMapperImple包">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值