spring和mybatis整合代码
spring和mybatis整合
1.整合思路
需要spring通过单例方式管理SqlSessionFactory。
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
持久层的mapper都需要由spring进行管理。
2.整合环境
创建一个新的java工程(接近实际开发的工程结构)
jar包:
mybatis3.2.7的jar包
spring3.2.0的jar包
mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,mybatis和spring整合由mybatis提供。jar包名mybatis-spring-1.2.2.jar
下面加入MyBatis与Spring整合的全部jar包
如图
工程结构:
如图
3.sqlSessionFactory
在applicationContext.xml配置sqlSessionFactory和数据源
sqlSessionFactory在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: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>
- <!-- sqlSessinFactory -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <!-- 加载mybatis的配置文件 -->
- <property name="configLocation" value="mybatis/SqlMapConfig.xml" />
- <!-- 数据源 -->
- <property name="dataSource" ref="dataSource" />
- </bean>
- </beans>
4.原始dao开发(和spring整合后)
4.1User.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">
- <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
- 注意:使用mapper代理方法开发,namespace有特殊重要的作用 -->
- <mapper namespace="test">
- <!-- 在映射文件中配置很多sql语句 -->
- <!-- 需求:通过id查询用户表的记录 -->
- <!-- 通过select执行数据库查询,
- id:标示映射文件中的sql,成为Statement的id
- 将sql语句封装到mappedStatement对象中,所以将id称为statement的id,
- parameterType:指定输入参数的类型,
- #{}标示一个占位符,
- #{id}其中id表示接收输入参数的名称,如果输入参数是简单类型,那么#{}中的值可以任意(如value)。
- resultType:指定sql输出结果的映射的java对象类型,
- select指定resultType表示将单条记录映射成java对象-->
- <select id="findUserById" parameterType="int" resultType="cn.edu.hpu.ssm.po.User">
- SELECT * FROM USER WHERE id=#{id}
- </select>
- </mapper>
在SqlMapconfig.xml中加载User.xml
- <!-- 加载映射文件 -->
- <mappers>
- <!-- 通过resource方法一次加载一个映射文件 -->
- <mapper resource="sqlmap/User.xml"/>
- <!-- 批量加载mapper-->
- <package name="cn.edu.hpu.ssm.mapper"/>
- </mappers>
4.2dao(实现类继承SqlSessionDaoSupport)
dao接口实现类需要注入SqlSessoinFactory,通过spring进行注入。
这里spring声明配置方式,配置dao的bean:
让UserDaoImpl实现类继承SqlSessionDaoSupport
4.3配置dao
首先创建UserDao接口和UserDaoImpl接口实现
UserDao.java:
- package cn.edu.hpu.ssm.dao;
- import cn.edu.hpu.ssm.po.User;
- //用户管理的Dao接口
- public interface UserDao{
- //根据Id查询用户信息
- public User findUserById(int id) throws Exception;
- }
UserDaoImpl.java:
- package cn.edu.hpu.ssm.dao;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- import cn.edu.hpu.ssm.po.User;
- public class UserDaoImpl implements UserDao{
- //需要向dao实现类中注入SqlSessionFactory工厂
- //这里我们暂时没用spring,我们通过构造方法注入
- private SqlSessionFactory sqlSessionFactory;
- public UserDaoImpl(SqlSessionFactory sqlSessionFactory){
- this.sqlSessionFactory=sqlSessionFactory;
- }
- public User findUserById(int id) throws Exception {
- SqlSession sqlSession=sqlSessionFactory.openSession();
- User user=sqlSession.selectOne("test.findUserById",id);
- //释放资源
- sqlSession.close();
- return user;
- }
- }
在applicationContext.xml中配置dao。
- <?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: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>
- <!-- sqlSessinFactory -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <!-- 加载mybatis的配置文件 -->
- <property name="configLocation" value="mybatis/SqlMapConfig.xml" />
- <!-- 数据源 -->
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!-- 原始Dao接口 -->
- <bean id="userDao" class="cn.edu.hpu.ssm.dao.UserDaoImpl">
- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
- </bean>
- </beans>
让UserDaoImpl去继承SqlSessionDaoSupport类,在SqlSessionDaoSupport类中提供了set和getsqlSessionFactory的方法。
- package cn.edu.hpu.ssm.dao;
- import org.apache.ibatis.session.SqlSession;
- import org.mybatis.spring.support.SqlSessionDaoSupport;
- import cn.edu.hpu.ssm.po.User;
- public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
- public User findUserById(int id) throws Exception {
- //继承SqlSessionDaoSupport类,通过this.getSqlSession()得到sqlSession
- SqlSession sqlSession=this.getSqlSession();
- User user=sqlSession.selectOne("test.findUserById",id);
- return user;
- }
- }
4.4测试程序
- package cn.edu.hpu.ssm.test;
- import org.junit.Before;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import cn.edu.hpu.ssm.dao.UserDao;
- import cn.edu.hpu.ssm.po.User;
- public class UserDaoImplTest {
- private ApplicationContext applicationContext;
- //注解Before是在执行本类所有测试方法之前先调用这个方法
- @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");
- //调用UserDao的方法
- User user=userDao.findUserById(1);
- //输出用户信息
- System.out.println(user.getId()+":"+user.getUsername());
- }
- }
测试结果和输出日志:
- DEBUG [main] - Creating a new SqlSession
- DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d] was not registered for synchronization because synchronization is not active
- DEBUG [main] - Fetching JDBC Connection from DataSource
- DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
- DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=?
- DEBUG [main] - ==> Parameters: 1(Integer)
- DEBUG [main] - <== Total: 1
- DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@8dcd5d]
- DEBUG [main] - Returning JDBC Connection to DataSource
- 1:张明明
5.mapper代理开发
5.1mapper.xml和mapper.java
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="cn.edu.hpu.ssm.mapper.UserMapper">
- <select id="findUserById" parameterType="int" resultType="cn.edu.hpu.mybatis.po.User">
- SELECT * FROM USER WHERE id=#{id}
- </select>
- </mapper>
UserMapper.java:
- package cn.edu.hpu.ssm.mapper;
- import cn.edu.hpu.ssm.po.User;
- //用户管理的Dao接口
- public interface UserMapper {
- //根据Id查询用户信息
- public User findUserById(int id) throws Exception;
- }
5.2通过MapperFactoryBean创建代理对象
- <!-- mapper配置
- MapperFactoryBean根据mapper接口生成mapper代理对象-->
- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
- <!-- mapperInterface指定mapper接口 -->
- <property name="mapperInterface" value="cn.edu.hpu.ssm.mapper.UserMapper"/>
- <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
- </bean>
此方法问题:
需要针对每个mapper进行配置,麻烦。所以要通过MapperScannerConfigurer进行mapper扫描。
5.3通过MapperScannerConfigurer进行mapper扫描(建议使用)
- <!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注入
- 遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中.
- 自动扫描出来的mapper的bean的id为mapper类名(首字母小写)-->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <!-- 指定扫描的包名
- 如果扫描多个包,每个包中间使用半角逗号分隔 -->
- <property name="basePackage" value="cn.edu.hpu.ssm.mapper"/>
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
- </bean>
sqlMapperConfig.xml中的mapper扫描就可以不要了
- <!-- 加载映射文件 -->
- <mappers>
- <!-- 通过resource方法一次加载一个映射文件 -->
- <mapper resource="sqlmap/User.xml"/>
- <!-- 批量加载mapper
- 和spring整合后,使用mapper扫描器,这里不需要配置了-->
- <!--<package name="cn.edu.hpu.ssm.mapper"/>-->
- </mappers>
5.4测试代码
- package cn.edu.hpu.ssm.test;
- import org.junit.Before;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import cn.edu.hpu.ssm.mapper.UserMapper;
- import cn.edu.hpu.ssm.po.User;
- public class UserMapperTest {
- private ApplicationContext applicationContext;
- //注解Before是在执行本类所有测试方法之前先调用这个方法
- @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.getId()+":"+user.getUsername());
- }
- }
测试结果及输出日志:
- DEBUG [main] - Returning cached instance of singleton bean 'userMapper'
- DEBUG [main] - Creating a new SqlSession
- DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a] was not registered for synchronization because synchronization is not active
- DEBUG [main] - Fetching JDBC Connection from DataSource
- DEBUG [main] - JDBC Connection [jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8, UserName=root@localhost, MySQL-AB JDBC Driver] will not be managed by Spring
- DEBUG [main] - ==> Preparing: SELECT * FROM USER WHERE id=?
- DEBUG [main] - ==> Parameters: 1(Integer)
- DEBUG [main] - <== Total: 1
- DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@13b5a3a]
- DEBUG [main] - Returning JDBC Connection to DataSource
- 1:张明明
转载请注明出处:http://blog.csdn.net/acmman/article/details/46906717
spring和mybatis整合代码相关推荐
- java元婴期(26)----java进阶(mybatis(5)---spring和mybatis整合(重点)逆向工程(会用))
spring和mybatis整合 1.整合思路 需要spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用SqlSessionFactor ...
- Spring+SpringMVC +MyBatis整合配置文件案例66666
Spring+SpringMVC +MyBatis整合配置文件案例 标签: springspringmvcmybatismvcjava 2017-04-13 19:12 228人阅读 评论(1) 收藏 ...
- spring和mybatis整合:使用xml方式
文章目录 spring和mybatis整合:使用xml方式 1. 创建数据库 2. 创建工程,pom.xml文件如下: 3. 依赖下载地址如下: 4. 配置mybatis的全局配置,在resource ...
- (八)Spring与MyBatis整合
持久层 目录 Mybatis 开发步骤回顾 Mybatis 开发中存在的问题 Spring 与 Mybatis 整合思路 Spring 与 Mybatis 整合的开发步骤 Spring 与 Mybat ...
- Spring和Mybatis整合
9. Spring和Mybatis整合 9.1 创建工程 新建工程,导入所需jar包: <dependencies><!-- mybatis核心包 --><depende ...
- Spring boot Mybatis 整合(完整版)
Spring boot Mybatis 整合(完整版) 更多干货 SpringBoot系列目录 正题 本项目使用的环境: 开发工具:Intellij IDEA 2017.1.3 springboot: ...
- 【Spring 持久层】Spring 与 Mybatis 整合
持久层 持久层整合总述 Mybatis 开发步骤回顾 Mybatis 开发中存在的问题 Spring 与 Mybatis 整合思路 Spring 与 Mybatis 整合的开发步骤 Spring 与 ...
- SpringMvc、Spring和Mybatis整合(SSM框架整合)
SpringMvc.Spring和Mybatis整合 就是我们通常的SSM整合. 先创建一个web的Maven项目. 1.SpringMvc环境搭建 1.1 导入SpringMvc所需要的依赖 在项目 ...
- Spring、Mybatis整合Service优化思路,DAO层、Service层最终编码以及log4j日志的使用
5. Spring.Mybatis整合Service层事务控制优化思路分析 # spring中处理事务的两种方式1. 编程式事务处理定义:通过在业务层中注入事务管理器对象,然后通过编码的方式进行事务控 ...
- Spring+ Spring mvc+MyBatis整合
Spring+ Spring mvc+MyBatis整合 目录结构 (1) 修改web.xml配置文件的内容 (2) 添加mybatis.spring mvc.spring database的xml文 ...
最新文章
- 理解 Delphi 的类(十) - 深入方法[23] - 重载
- 关于github failed to push some refs
- sencha touch 模仿tabpanel导航栏TabBar(2013-11-7)
- OC特有语法:分类category,给NSString增加方法计算字符串中数字的个数
- 创建一个dynamics CRM workflow (二) - Build in Workflows
- [转] C# TextBox、DataGrideView中的数据绑定
- Java基础之GC回收
- JAVA读取2g数据的速度_Java 读取大容量excel
- POJ 3614 Sunscreen
- Linux系列在线培训五月盛情开幕!!(5月9日,10日,16日,17日,23日,24日)18:30 - 21:30,
- js 一个对象的属性名是一个变量如何设置和获取值
- python语言的读法-python是什么语言编写的
- 《神经网络和深度学习》系列文章七:实现我们的神经网络来分类数字(下)...
- 头衔的权威暗示影响力
- 一道有关switch-case题目
- 注意丨Pearson VUE身份证件政策要求
- 【小程序】小程序里跳转网页链接
- c语言用switch编写春夏秋冬,利用switch实现春夏秋冬
- 【滤波器】6. 高通滤波器
- 如何获取CSDN积分(下载分)
热门文章
- JDBC的使用(msql);
- Java Scanner 类,获取用户输入的值
- 【Java】 大话数据结构(5) 线性表之双向链表
- 使用Spring的AbstractRoutingDataSource实现多数据源切换
- Django进阶之CSRF
- 安卓WindowManager注入事件如何跳出进程间安全限制
- Ubuntu下打开windows的txt文件乱码解决
- 《python3网络爬虫开发实战》--Ajax数据爬取
- 机器学习之路: python 决策树分类DecisionTreeClassifier 预测泰坦尼克号乘客是否幸存...
- C#之四十二 C# 读写文本文件乱码解决方案