设为首页 收藏本站
查看: 873|回复: 0

[经验分享] MyBatis与Spring集成

[复制链接]

尚未签到

发表于 2016-11-24 08:19:21 | 显示全部楼层 |阅读模式
  Spring2只支持iBatis2,Spring3是不支持MyBatis3的,所以MyBatis自开发了一个集成Spring框架的项目MyBatis-Spring。该项目集成Spring,可以将事务交给Spring进行管理,同时将mapper类、sqlSession注入到其它类中。
  项目地址:https://github.com/mybatis/spring
官方帮助文档(英文):http://mybatis.github.io/spring/index.html
官方帮助文档(中文):http://mybatis.github.io/spring/zh/index.html
  MyBatis进行数据处理的核心是SqlSession,SqlSession又通过SqlSessionFactory产生,在MyBatis 中SqlSessionFactory由SqlSessionFactoryBuilder创建,与Spring集成后通过 SqlSessionFactoryBean产生。SqlSession的创建方式有两种:一种是通过SqlSessionTemplate创建,还有一 种是通过继承SqlSessionDaoSupport后调用getSqlSession方法获得。其实还有一种隐式的创建方式是通过自动扫描 Mapper类,然后框架会自动注入SqlSession。
  具体的配置方式如下:
  
(1)spring-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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.research.mybatis"></context:component-scan>
<!-- 创建SqlSessionFactory,同时指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation"
value="classpath:generator/spring/spring-mybatis-config.xml"></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;generateSimpleParameterMetadata=true" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- 方式1、使用继承SqlSessionDaoSupport方式 -->
<bean id="mybatisSpringDaoUseDaoSupport"
class="com.research.mybatis.spring.MybatisSpringDaoUseDaoSupport">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 方式2、使用sqlSessionTemplate方式 -->
<bean id="mybatisSpringDaoUseTemplate" class="com.research.mybatis.spring.MybatisSpringDaoUseTemplate">
<property name="sqlSession" ref="sqlSession"></property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"></constructor-arg>
</bean>
<!-- 方式3、使用扫描Mapper类的方式 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="basePackage" value="com.research.mybatis.generator.dao"></property>
</bean>
</beans>
  
(2)spring-mybatis-config.xml:这个是MyBatis相关的配置,不需要配置太多,因为集成的时候环境配置、数据源配置、事务配置都交给Spring去管理了。

<?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>
<typeAlias alias="AgentInvokeGenerate" type="com.research.mybatis.generator.model.AgentInvokeGenerate"/>
</typeAliases>
<mappers>
<mapper resource="generator/mapper/AgentInvokeGenerateMapper.xml"></mapper>
</mappers>
</configuration>
  (3)AgentInvokeGenerateMapper.xml:具体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.research.mybatis.generator.dao.AgentInvokeGenerateMapper">
<resultMap id="BaseResultMap" type="com.research.mybatis.generator.model.AgentInvokeGenerate">
<id column="ID" jdbcType="CHAR" property="ID" />
<result column="DB_FLAG" jdbcType="VARCHAR" property="dbFlag" />
<result column="STATUS" jdbcType="CHAR" property="STATUS" />
</resultMap>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from agent_info
where ID = #{ID,jdbcType=CHAR}
</select>
</mapper>
  具体调用的代码如下:
  
(1)使用SqlSessionTemplate方式:

package com.research.mybatis.spring;
import org.apache.ibatis.session.SqlSession;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
public class MybatisSpringDaoUseTemplate {
private SqlSession sqlSession;
public AgentInvokeGenerate getAgentInvokeById(String id){
return sqlSession.selectOne("com.research.mybatis.generator.dao.AgentInvokeGenerateMapper.selectByPrimaryKey", id);
}
public SqlSession getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}     
}

  (2)使用SqlSessionDaoSupport方式:

package com.research.mybatis.spring;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
@Repository
public class MybatisSpringDaoUseDaoSupport extends SqlSessionDaoSupport{
public AgentInvokeGenerate getAgentInvokeById(String id){
return getSqlSession().selectOne("com.research.mybatis.generator.dao.AgentInvokeGenerateMapper.selectByPrimaryKey", id);
}
}

  (3)使用Mapper方式:

package com.research.mybatis.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.research.mybatis.generator.dao.AgentInvokeGenerateMapper;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
@Repository
public class MybatisSpringDaoUseMapper {
@Autowired
private AgentInvokeGenerateMapper mapper;
public AgentInvokeGenerate getAgentInvokeById(String id){
return mapper.selectByPrimaryKey(id);
}
}

  相关实体类和Mapper类:

package com.research.mybatis.generator.model;
public class AgentInvokeGenerate {
private String ID;
private String dbFlag;
private String STATUS;
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID == null ? null : ID.trim();
}
public String getDbFlag() {
return dbFlag;
}
public void setDbFlag(String dbFlag) {
this.dbFlag = dbFlag == null ? null : dbFlag.trim();
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String STATUS) {
this.STATUS = STATUS == null ? null : STATUS.trim();
}
}

package com.research.mybatis.generator.dao;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
public interface AgentInvokeGenerateMapper {
AgentInvokeGenerate selectByPrimaryKey(String ID);
}
  具体测试类如下(使用TestNG):
  
(1)使用SqlSessionTemplate方式的测试类:

package com.research.mybatis.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
@ContextConfiguration(locations="classpath:/generator/spring/spring-mybatis.xml")
public class MybatisSpringDaoUseTemplateTest extends AbstractTestNGSpringContextTests{
@Autowired
private MybatisSpringDaoUseTemplate dao;
@Test
public void getAgentInvokeById() {
String id = "001";
AgentInvokeGenerate ai = dao.getAgentInvokeById(id);
Assert.assertTrue("000".equals(ai.getDbFlag()));
}
}

  (2)使用SqlSessionDaoSupport方式的测试类:

package com.research.mybatis.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
@ContextConfiguration(locations="classpath:/generator/spring/spring-mybatis.xml")
public class MybatisSpringDaoUseDaoSupportTest extends AbstractTestNGSpringContextTests{
@Autowired
private MybatisSpringDaoUseDaoSupport dao;
@Test
public void getAgentInvokeById() {
String id = "001";
AgentInvokeGenerate ai = dao.getAgentInvokeById(id);
Assert.assertTrue("000".equals(ai.getDbFlag()));
}
}

  (3)使用Mapper方式的测试类:

package com.research.mybatis.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.research.mybatis.generator.model.AgentInvokeGenerate;
@ContextConfiguration(locations="classpath:/generator/spring/spring-mybatis.xml")
public class MybatisSpringDaoUseMapperTest extends AbstractTestNGSpringContextTests{
@Autowired
private MybatisSpringDaoUseMapper dao;
@Test
public void getAgentInvokeById() {
String id = "001";
AgentInvokeGenerate ai = dao.getAgentInvokeById(id);
Assert.assertTrue("000".equals(ai.getDbFlag()));
}
}

  代码测试通过,若用博文中代码时需注意下文件和包路径是否正确,更多集成相关的细节参考官方帮助文档

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-304669-1-1.html 上篇帖子: Hibernate与MyBatis 下篇帖子: mybatis优化(转)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表