Spring(7):Mybatis 与 Spring 整合小结与实例分析(上)
2017-12-30 14:42
489 查看
2017/12/28
Spring和Mybatis的核心是什么?
Spring的核心:IOC和AOP;单干的时候,就新建了一个applicationContext.xml,然后添加各种各样的Bean,与之对应的必要的实体类;的的确确省事省心,避免了大量冗余代码;
Mybatis的核心:SQL与实体对象的映射;单干的时候,就新建了一个mybatis-config.xml作全局配置,mapper.xml作sql映射配置,然后添加各个实体类和相关的操作接口,的的确确方便,避免一次次的jdbc连接断开;
那么要如何将两者结合到一起呢,它们之间的依赖关系是什么?
回答:
(1)spring的ioc机制,可以接管组件创建工作和依赖管理,所以“整合”主要工作就是把Mybatis框架涉及的核心组件配置到Spring容器里;
(2)Spring是老大,Mybatis是手下;业务逻辑对象依赖基于Mybatis技术实现的DAO对象,核心是获取SQLSession实例。在此之前还有依赖SQLSessionFactory实例。在此之前需要依赖SQLSessionFactoryBuilder从数据源、SQL映射文件等信息构建。
随着引入Spring框架,以上流程将全部移交给Spring,发挥Spring框架Bean容器的作用,接管创建工作和管理组件生命周期,对组件之间的依赖关系进行解耦合管理。
下面是Spring框架对Mybatis框架的一个整合示例,主要方便各位捋顺思路,抛砖引玉。
【1】导入所需的 jar 包
![](https://oscdn.geek-share.com/Uploads/Images/Content/202009/14/7d38c4fe86428db6cd6b8ff7b378ef37)
图1
开发文件框架:
![](https://oscdn.geek-share.com/Uploads/Images/Content/202009/14/3a31afca1799ac3a4bd6e0d9ffc3a328)
图2
【2】建立开发目录,创建实体类User.java:
【3】创建实体类User的DAO接口UserMapper.java:
【4】新建UserMapper.java文件,配置SQL映射文件:
【5】新建mybatis-config.xml文件,并配置,内容很少:
【6】实现Spring对Mybatis的整合--
6.1 配置数据源,添加两个jar包(commons-logging-1.0.4.jar + commons-dbcp-1.4.jar),新建applicationContext-mybatis.xml 配置文件
;
在 applicationContext-mybatis.xml 进行数据源配置代码:
6.2 配置SqlSessionFactoryBean;
在 applicationContext-mybatis.xml 进行SqlSessionFactoryBean配置代码:
6.3 配置SqlSessionTemplate:
Mybatis-Spring整合包提供了SQLSessionTemplate类,实现了Mybatis的SQLSession接口,可以替换Mybatis原有的SQLSession实现类,提供数据库访问操作。所以,配置SqlSessionTemplate,并在UserMapper实现类中使用的代码;
新建UserMapperImpl.java文件:
在 applicationContext-mybatis.xml 进行SqlSessionTemplate配置代码:
【7】至此,配置工作大致完成,下面是业务文件的编写:
新建业务接口 UserService.java:
新建业务接口实现类 UserServiceImpl.java:
在applicationContext-mybatis.xml 对业务类编写bean配置:
【8】applicationContext-mybatis.xml 配置文件的完整代码:
【9】编写测试类 UserServiceImpTest.java(调用业务类的方法):
【10】输出结果:
综上,以上是Spring对Mybatis的整合实例。注意特征:我们将Mapper接口实现了,然后调用方法才能访问数据库,是因为在实现类中有SqlSessionTemplate的存在。但是,之后我会总结另一个方法,将不用把接口实现,就能访问数据库,这也是Spring框架带来的好处。
Spring和Mybatis的核心是什么?
Spring的核心:IOC和AOP;单干的时候,就新建了一个applicationContext.xml,然后添加各种各样的Bean,与之对应的必要的实体类;的的确确省事省心,避免了大量冗余代码;
Mybatis的核心:SQL与实体对象的映射;单干的时候,就新建了一个mybatis-config.xml作全局配置,mapper.xml作sql映射配置,然后添加各个实体类和相关的操作接口,的的确确方便,避免一次次的jdbc连接断开;
那么要如何将两者结合到一起呢,它们之间的依赖关系是什么?
回答:
(1)spring的ioc机制,可以接管组件创建工作和依赖管理,所以“整合”主要工作就是把Mybatis框架涉及的核心组件配置到Spring容器里;
(2)Spring是老大,Mybatis是手下;业务逻辑对象依赖基于Mybatis技术实现的DAO对象,核心是获取SQLSession实例。在此之前还有依赖SQLSessionFactory实例。在此之前需要依赖SQLSessionFactoryBuilder从数据源、SQL映射文件等信息构建。
随着引入Spring框架,以上流程将全部移交给Spring,发挥Spring框架Bean容器的作用,接管创建工作和管理组件生命周期,对组件之间的依赖关系进行解耦合管理。
下面是Spring框架对Mybatis框架的一个整合示例,主要方便各位捋顺思路,抛砖引玉。
【1】导入所需的 jar 包
图1
开发文件框架:
图2
【2】建立开发目录,创建实体类User.java:
package com.smbms.pojo; import java.util.Date; import java.util.List; public class User implements java.io.Serializable{ private Integer id; private String userCode; private String userName; private String userPassword; private Integer gender; private Date birthday; private String phone; private String address ; private Integer userRole; private Integer createdBy; private Date creationDate; private Integer modifyBy; private Date modifyDate; private String userRoleName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getUserRole() { return userRole; } public void setUserRole(Integer userRole) { this.userRole = userRole; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public String getUserRoleName() { return userRoleName; } public void setUserRoleName(String userRoleName) { this.userRoleName = userRoleName; } public User() { super(); // TODO 自动生成的构造函数存根 } }
【3】创建实体类User的DAO接口UserMapper.java:
package com.smbms.pojo; import java.util.List; import com.smbms.pojo.User; public interface UserMapper { /** * 下面定义的方法是用于--Mybatis/Spring整合练习。 * */ public List<User> getUserList(User user); }
【4】新建UserMapper.java文件,配置SQL映射文件:
<?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.smbms.pojo.UserMapper"> <!-- 下面定义的映射语句是用于Mybatis/Spring整合练习。 --> <resultMap type="com.smbms.pojo.User" id="userlist"> <result property="userRoleName" column="roleName"/> </resultMap> <select id="getUserList" parameterType="com.smbms.pojo.User" resultMap="userlist"> select u.* ,r.roleName from smbms_user u ,smbms_role r where u.userName like CONCAT('%',#{userName},'%') and u.userRole = #{userRole} and u.userRole = r.id </select> </mapper>
【5】新建mybatis-config.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.smbms.pojo"/> </typeAliases> </configuration>
【6】实现Spring对Mybatis的整合--
6.1 配置数据源,添加两个jar包(commons-logging-1.0.4.jar + commons-dbcp-1.4.jar),新建applicationContext-mybatis.xml 配置文件
;
在 applicationContext-mybatis.xml 进行数据源配置代码:
<!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url"> <value><![CDATA[jdbc:mysql://127.0.0.1:3306/test? useUnicode=true&characterEncoding=utf-8]]></value> </property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean>
6.2 配置SqlSessionFactoryBean;
在 applicationContext-mybatis.xml 进行SqlSessionFactoryBean配置代码:
<!-- SqlSessionFactoryBean 配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引用数据源组件 --> <property name="dataSource" ref="dataSource"></property> <!-- 引用Mybatis配置文件的配置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 配置SQL映射文件信息 ,逐个列出SQL映射文件麻烦,所以使用 mapperLocations 属性扫描加载SQL映射文件--> <property name="mapperLocations"> <list> <value>classpath:com/smbms/pojo/**/*.xml</value> </list> </property> </bean>
6.3 配置SqlSessionTemplate:
Mybatis-Spring整合包提供了SQLSessionTemplate类,实现了Mybatis的SQLSession接口,可以替换Mybatis原有的SQLSession实现类,提供数据库访问操作。所以,配置SqlSessionTemplate,并在UserMapper实现类中使用的代码;
新建UserMapperImpl.java文件:
package com.smbms.pojo; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import com.smbms.pojo.User; public class UserMapperImpl implements UserMapper{ private SqlSessionTemplate sqlSession; @Override public List<User> getUserList(User user) { return sqlSession.selectList("com.smbms.pojo.UserMapper.getUserList",user); } public SqlSessionTemplate getSqlSession() { return sqlSession; } public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public UserMapperImpl() { super(); // TODO 自动生成的构造函数存根 } public UserMapperImpl(SqlSessionTemplate sqlSession) { super(); this.sqlSession = sqlSession; } }
在 applicationContext-mybatis.xml 进行SqlSessionTemplate配置代码:
<!-- 配置SQLSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> <!-- 配置DAO组件并进入SQLSessionTemplate实例 --> <bean id="userMapper" class="com.smbms.pojo.UserMapperImpl"> <constructor-arg name="sqlSession" ref="sqlSessionTemplate"></constructor-arg> </bean>
【7】至此,配置工作大致完成,下面是业务文件的编写:
新建业务接口 UserService.java:
package com.smbms.pojo; import java.util.List; public interface UserService { public List<User> findUsersWithConditions(User user); }
新建业务接口实现类 UserServiceImpl.java:
package com.smbms.pojo; import java.util.List; public class UserServiceImpl implements UserService{ private UserMapper userMapper; @Override public List<User> findUsersWithConditions(User user) { try{ return userMapper.getUserList(user); }catch(RuntimeException e){ e.printStackTrace(); throw e; } } public UserMapper getUserMapper() { return userMapper; } public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } }
在applicationContext-mybatis.xml 对业务类编写bean配置:
<!-- 配置业务Bean并注入DAO实例 --> <bean id="userService" class="com.smbms.pojo.UserServiceImpl"> <property name="userMapper" ref="userMapper"></property> </bean>
【8】applicationContext-mybatis.xml 配置文件的完整代码:
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url">
<value><![CDATA[jdbc:mysql://127.0.0.1:3306/test?
useUnicode=true&characterEncoding=utf-8]]></value>
</property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<!-- SqlSessionFactoryBean 配置 -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据源组件 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 引用Mybatis配置文件的配置 -->
<property name="configLocation"
value="classpath:mybatis-config.xml"></property>
<!-- 配置SQL映射文件信息 ,逐个列出SQL映射文件麻烦,所以使用 mapperLocations 属性扫描加载SQL映射文件-->
<property name="mapperLocations">
<list>
<value>classpath:com/smbms/pojo/**/*.xml</value>
</list>
</property>
</bean>
<!-- 配置SQLSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> <!-- 配置DAO组件并进入SQLSessionTemplate实例 --> <bean id="userMapper" class="com.smbms.pojo.UserMapperImpl"> <constructor-arg name="sqlSession" ref="sqlSessionTemplate"></constructor-arg> </bean>
<!-- 配置业务Bean并注入DAO实例 -->
<bean id="userService" class="com.smbms.pojo.UserServiceImpl">
<property name="userMapper" ref="userMapper"></property>
</bean>
</beans>
【9】编写测试类 UserServiceImpTest.java(调用业务类的方法):
package com.smbms.pojo; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UserServiceImpTest { @SuppressWarnings("resource") @Test public void test() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml"); UserService userService = (UserService)ctx.getBean("userService"); User userCondition = new User(); userCondition.setUserName("mmb"); userCondition.setUserRole(110); List<User> userList = new ArrayList<User>(); userList = userService.findUsersWithConditions(userCondition); for(User userResult:userList){ System.out.println("testGetUserList userCode:"+userResult.getUserCode()+ "userName: "+userResult.getUserName()+ "userRole: "+userResult.getUserRole()+ "userRoleName: "+userResult.getUserRoleName()+ "userAddress: "+userResult.getCreationDate()); } } }
【10】输出结果:
testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null testGetUserList userCode:test01userName: mmb02userRole: 110userRoleName: guan_li_yuanuserAddress: null
综上,以上是Spring对Mybatis的整合实例。注意特征:我们将Mapper接口实现了,然后调用方法才能访问数据库,是因为在实现类中有SqlSessionTemplate的存在。但是,之后我会总结另一个方法,将不用把接口实现,就能访问数据库,这也是Spring框架带来的好处。
相关文章推荐
- Spring(7):Mybatis 与 Spring 整合小结与实例分析--从Log分析Spring的工作流程(下)
- SpringMVC+Mybatis整合实例及功能分析
- Spring+SpringMVC+MyBatis整合实例
- Spring源码分析总结——Mybatis的整合
- springboot+mybatis+springmvc整合实例
- 如何整合Spring和Mybatis的思路分析(整合的是原生的Dao)
- Spring+SpringMVC+mybatis+easyui整合实例(一)实例介绍
- Spring与Mybatis整合的MapperScannerConfigurer处理过程源码分析
- maven项目下的Spring+SpringMVC+Mybatis整合实例
- spring mvc+mybatis整合实例讲解
- springboot与mybatis整合实例详解
- Spring + mybatis整合方案总结 结合实例应用
- spring boot整合mybatis的详细实例
- Spring MVC+Mybatis+Maven+Velocity+Mysql整合实例
- Spring与Mybatis整合的MapperScannerConfigurer处理过程源码分析/mybatis中文官方文档
- Spring+SpringMVC+Mybatis整合开发实践(含源码(两个整合实例)、PPT)
- Spring + SpringMVC + MyBatis (SSM)整合实例
- Spring+SpringMVC+Mybatis+Mysql整合实例
- Spring+SpringMVC+mybatis+easyui整合实例(四)easyUI界面部分
- springboot整合mybatis将sql打印到日志的实例详解