Mybatis学习(7)spring和mybatis整合
整合思路:
需要spring通过单例方式管理SqlSessionFactory。
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
持久层的mapper都需要由spring进行管理。
1)加入jar包:
mybatis3.2.7的jar包;spring3.2.0的jar包;
mybatis和spring的整合包:mybatis-spring-1.2.2.jar
2)applicationContext.xml配置文件:
3)其他db.properties;log4j.properties和之前的一样;
一、使用原始dao接口开发(和spring整合后):
工程结构:



User.xml:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test">
<select id="findUserById" parameterType="int" resultType="com.ssm.po.User">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>
SqlMapConfig.xml配置(加入User.xml的映射):
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.ssm.po"/>
</typeAliases> <!-- 加载 映射文件 -->
<mappers>
<mapper resource="sqlMap/User.xml"/>
</mappers>
</configuration>
UserDao接口:
package com.ssm.dao;
import com.ssm.po.User;
public interface UserDao {
//根据id查询用户信息
public User findUserById(int id) throws Exception;
}
UserDaoImpl实现类(继承SqlSessionDaoSupport):
dao接口实现类需要注入SqlSessoinFactory,通过spring进行注入。
package com.ssm.dao; import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.ssm.po.User; public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { @Override
public User findUserById(int id) throws Exception {
//继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSessoin
SqlSession sqlSession = this.getSqlSession();
User user = sqlSession.selectOne("test.findUserById", id);
return user;
}
}
applicationContext.xml配置:
配置sqlSessionFactory、数据源、等、声明式配置UserDao的bean:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean> <!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 原始dao接口 -->
<bean id="userDao" class="com.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
测试程序:
package com.ssm.dao; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ssm.po.User; public class UserDaoImplTest {
private ApplicationContext applicationContext; //在setUp这个方法得到spring容器
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
} @Test
public void testFindUserById() throws Exception {
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = userDao.findUserById(1);
System.out.println(user);
}
}
二、使用mapper接口代理的方式开发:
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ssm.mapper.UserMapper">
<select id="findUserById" parameterType="int" resultType="user">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>
UserMapper接口:和UserMapper.xml位于同目录下
package com.ssm.mapper;
import com.ssm.po.User;
public interface UserMapper {
//根据id查询用户信息
public User findUserById(int id) throws Exception;
}
在SqlMapConfig.xml中加载UserMapper.xml映射文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.ssm.po"/>
</typeAliases> <!-- 加载 映射文件 -->
<mappers>
<package name="com.ssm.mapper"/>
</mappers>
</configuration>
在applicationContext.xml中通过MapperFactoryBean创建代理对象:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean> <!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- mapper配置 MapperFactoryBean:根据mapper接口生成代理对象-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- mapperInterface指定mapper接口 -->
<property name="mapperInterface" value="com.ssm.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean> </beans>
测试代码:
package com.ssm.mapper; import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ssm.po.User; public class UserMapperTest {
private ApplicationContext applicationContext; @Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
} @Test
public void testFindUserById() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
} }
针对上面的applicationContext.xml中通过MapperFactoryBean创建代理对象,需要针对每个mapper进行配置,比较麻烦,
优化:通过MapperScannerConfigurer进行Mapper扫描:
于是applicationContext.xml配置修改为:
<!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名 如果扫描多个包,每个包中间使用半角逗号分隔-->
<property name="basePackage" value="com.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
而且和spring整合后,使用mapper扫描器,SqlMapConfig.xm这里不需要配置了
<!-- <package name="com.ssm.mapper"/> -->
----------------------------------------------------------------------------------------------------------------------------------------------------------
Mybatis学习(7)spring和mybatis整合的更多相关文章
- mybatis学习笔记 spring与mybatis整合
转载自http://blog.csdn.net/naruto_Mr/article/details/48239357 1.创建web工程,导入spring依赖包与mybatis依赖包,还需要mybat ...
- (转)SpringMVC学习(四)——Spring、MyBatis和SpringMVC的整合
http://blog.csdn.net/yerenyuan_pku/article/details/72231763 之前我整合了Spring和MyBatis这两个框架,不会的可以看我的文章MyBa ...
- MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql
目录(?)[-] 一MyBatis简介与配置MyBatisSpringMySql MyBatis简介 MyBatisSpringMySql简单配置 搭建Spring环境 建立MySql数据库 搭建My ...
- Quartz学习——SSMM(Spring+SpringMVC+Mybatis+Mysql)和Quartz集成详解(转)
通过前面的学习,你可能大致了解了Quartz,本篇博文为你打开学习SSMM+Quartz的旅程!欢迎上车,开始美好的旅程! 本篇是在SSM框架基础上进行的. 参考文章: 1.Quartz学习——Qua ...
- MyBatis学习 之 四、MyBatis配置文件
目录(?)[-] 四MyBatis主配置文件 properties属性 settings设置 typeAliases类型别名 typeHandlers类型句柄 ObjectFactory对象工厂 pl ...
- 【转】MyBatis学习总结(三)——优化MyBatis配置文件中的配置
[转]MyBatis学习总结(三)——优化MyBatis配置文件中的配置 一.连接数据库的配置单独放在一个properties文件中 之前,我们是直接将数据库的连接配置信息写在了MyBatis的con ...
- 【转】MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
[转]MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据, ...
- spring学习 六 spring与mybatis整合
在mybatis学习中有两种配置文件 :全局配置文件,映射配置文件.mybatis和spring整合,其实就是把mybatis中的全局配置文件的配置内容都变成一个spring容器的一个bean,让sp ...
- Spring学习之Spring与Mybatis的两种整合方式
本机使用IDEA 2020.1.MySql 8.0.19,通过Maven进行构建 环境准备 导入maven依赖包 <dependencies> <dependency> < ...
- MyBatis学习(四)MyBatis和Spring整合
MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...
随机推荐
- 剑指offer 数字在排序数组中出现的次数
因为有序 所以用二分法,分别找到第一个k和最后一个k的下标.时间O(logN) class Solution { public: int GetNumberOfK(vector<int> ...
- php通过token验证表单重复提交
PHP防止重复提交表单 2016-11-08 轻松学PHP 我们提交表单的时候,不能忽视的一个限制是防止用户重复提交表单,因为有可能用户连续点击了提交按钮或者是攻击者恶意提交数据,那么我们在提交数据后 ...
- HDU 1883 Phone Cell(计算几何)
方法:选取一个点A,以点A为圆心做一个半径为r的圆,然后枚举另一个点B,以B为圆心做一个圆,如果这两个圆有交集,那我们在这个交集内选取一个点做半径为r的圆,这个圆就包括了A和B点,找到交集最多的区域并 ...
- jdbc批量执行SQL insert 操作
package com.file; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayLi ...
- JS面向对象基础
以往写代码仅仅是为了实现特定的功能,后期维护或别人重用的时候,困难很大. Javascript作为完全面向对象的语言,要写出最优的代码,需要理解对象是如何工作的. 1. 对象是javasc ...
- Java时间操作(一):关于UTC格式时间处理
Java中获取形如:20160811T122132+08 格式,可以通过如下方法 package com.mc.others; public class UTCTimeTest { @Test pub ...
- HDU 2167 Pebbles(状压DP)
题目链接:Pebbles Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Tota ...
- Android网络开发之Volley--Volley基本用法JsonObjectReques(二)
1.JsonObjectRequest用法 用法和StringRequest基本相同,主要分为3步: (1).实例化一个RequestQueue对象 (2).设置JsonObjectRequest对象 ...
- stm32 RAM分配及占有(转)
源:http://blog.chinaunix.net/uid-26921272-id-4550126.html 一个小的项目,在测试时间和产品量稍微大一些之后,出现了一些莫名其妙的非逻辑错误的Bug ...
- ASP.NET MVC 5 WEB API 用户验证
参考博客:ASP.NET MVC5+EF6+EasyUI 后台管理系统(65)-MVC WebApi 用户验证 (1) 参考博客:MVC WebApi 用户验证 (2)构建ASP.NET MVC5+E ...