欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis与Spring集成

程序员文章站 2022-05-31 21:28:53
...

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()));
  }
}

 

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