Spring整合Mybatis的集成方式

1、采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。

<?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"
	   xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

	<!-- 自动扫描注解,管理bean -->
	<context:component-scan base-package="com.pay.service">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
	</context:component-scan>

	<context:component-scan base-package="com.pay.model,com.pay.dto">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
	</context:component-scan>

	<!-- 1.1 加载数据库配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>

	<!--开启注解方式-->
	<context:annotation-config/>

	<!-- 1.2 配置Druid数据源 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 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="initialSize" value="${initialSize}"/>
		<property name="minIdle" value="${minIdle}"/>
		<property name="maxActive" value="${maxActive}"/>

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="60000"/>

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="60000"/>

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="300000"/>
		<property name="validationQuery" value="SELECT 'x'"/>
		<property name="testWhileIdle" value="true"/>
		<property name="testOnBorrow" value="false"/>
		<property name="testOnReturn" value="false"/>

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
		<property name="poolPreparedStatements" value="true"/>
		<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>

		<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
		<property name="filters" value="stat"/>
	</bean>

	<!-- 1.3 Spring和MyBatis整合,配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据库连接池 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 配置 Mybatis 全局配置文件 -->
		<property name="configLocation" value="classpath:/config/mybatis-config.xml"/>
		<!-- 自动扫描mapping.xml文件 -->
		<property name="mapperLocations" value="classpath:/mapper/*.xml"/>
		<!--<property name="typeAliasesPackage" value="com.pay.model"/>-->
	</bean>

	<!-- 1.4 扫描Dao接口,Spring会自动查找其下的类,注入到spring容器中 包下的类需要使用@MapperScan注解-->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号分割 -->
		<property name="basePackage" value="com.pay.dao"/>
		<property name="sqlSessionTemplateBeanName" value="sqlSessionTemplate"/>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
	</bean>

	<!-- 启用sqlSessionTemplate来执行session的执行操作 -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory"/>
	</bean>

	<!-- 工具类 -->
	<bean id="beanFactoryUtil" class="com.pay.util.BeanFactoryUtil" lazy-init="false"/>

	<!-- druid 日志 -->
	<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
		<property name="statementExecutableSqlLogEnable" value="true"/>
	</bean>

	<!-- 事务管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!-- 配置事务的注解方式注入,开启对Class的动态代理功能 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 传播行为 -->
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="create*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	<!-- 切面 -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.pay.service.*.*(..))"/>
	</aop:config>

</beans>
<?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.pay.dao.IManagerDao">

  <!-- 缓存配置 -->
  <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>

  <resultMap id="ManagerResultMap" type="com.pay.model.Manager">
    <constructor>
      <idArg column="id" javaType="java.lang.Integer" jdbcType="INTEGER" />
      <arg column="userName" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="userPwd" javaType="java.lang.String" jdbcType="VARCHAR" />
      <arg column="email" javaType="java.lang.String" jdbcType="VARCHAR" />
    </constructor>
  </resultMap>
  <sql id="ManagerList">
    id, userName, userPwd, email
  </sql>

  <!-- 添加管理员 -->
  <insert id="add" parameterType="com.pay.model.Manager">
    insert into manager (userName, userPwd, email)
    values (#{username,jdbcType=VARCHAR}, #{userpwd,jdbcType=VARCHAR},
      #{email,jdbcType=VARCHAR})
  </insert>

  <!-- 删除管理员 -->
  <delete id="del" parameterType="Integer">
    DELETE from manager where id = #{id}
  </delete>

  <!-- 查询管理员 -->
  <select id="findUser" resultMap="ManagerResultMap">
    select <include refid="ManagerList"/> from manager where userName = #{userName} and userPwd = #{userPwd}
  </select>

  <select id="findAll" resultMap="ManagerResultMap" >
    SELECT * from manager
  </select>

  <!-- 更改管理员密码 -->
  <update id="updatePwd" parameterType="com.pay.model.Manager">
    UPDATE manager SET userPwd = #{userPwd} where userName = #{userName} and id = #{id}
  </update>

</mapper>
package com.pay.dao;

import com.pay.model.Manager;
import org.apache.ibatis.annotations.Param;
import org.mybatis.spring.annotation.MapperScan;

import java.util.List;

@MapperScan
public interface IManagerDao {
    /**
     * 添加一个管理员
     * @param bean 管理实体类
     */
    int add(Manager bean);

    /**
     * 查询管理用户
     * @param userName 用户名
     * @param userPwd 用户密码
     * @return 一个管理角色对象
     */
    Manager findUser(@Param("userName") String userName, @Param("userPwd") String userPwd);

    /**
     * 更改管理员密码
     * @param userName 用户名
     * @param newPwd 用户新密码
     */
    void updatePwd(String userName, String newPwd);

    /**
     * 查询所有管理员用户
     * @return 管理员集合
     */
    List<Manager> findAll();
}
package com.pay.service;

import com.pay.model.Manager;

import java.util.List;

/**
 * 管理员业务层
 * @author jalena
 *
 */
public interface IManagerService {
	/**
	 * 添加一个管理员
	 * @param bean 管理实体类
	 */
	int add(Manager bean);
	
	/**
	 * 查询管理用户
	 * @param userName 用户名
	 * @param userPwd 用户密码
	 * @return 一个管理角色对象
	 */
	Manager findUser(String userName, String userPwd);
	
	/**
	 * 更改管理员密码
	 * @param userName 用户名
	 * @param newPwd 用户新密码
	 */
	void updatePwd(String userName, String newPwd);
	
	/**
	 * 查询所有管理员用户
	 * @return 管理员集合
	 */
	List<Manager> findAll();
}
package com.pay.service.impl;

import com.pay.dao.IManagerDao;
import com.pay.model.Manager;
import com.pay.service.IManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Jalena
 * @create 2017-04-09 23:20
 */
@Service
@Transactional
public class IManagerServiceImpl implements IManagerService {

	@Autowired
	private IManagerDao dao;

	public int add(Manager bean) {
		return dao.add(bean);
	}

	public Manager findUser(String userName, String userPwd) {
		return dao.findUser(userName,userPwd);
	}

	public void updatePwd(String userName, String newPwd) {
		dao.updatePwd(userName,newPwd);
	}

	public List<Manager> findAll() {
		return dao.findAll();
	}
}

这种方式最好!


2、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
mybatis中, sessionFactory可由SqlSessionFactoryBuilder来创建。MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.hua.saf" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}" />
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation"  value="classpath:sqlMapConfig.xml"/>
        <!-- 自动扫描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中单独指定xml文件-->
        <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
    </bean>
    
    <!-- mybatis spring sqlSessionTemplate,使用时直接让spring注入即可 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
<?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 type="com.hua.saf.pojo.User" alias="User" />
    </typeAliases>
</configuration>
@Repository
public class UserDao{

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;
    
    public User getUser(int id) {
        return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1);
    }   
}
@Service
public class UserService{
    
    @Resource
    private UserDao userDao;
    
    public User getUser(int id) {
        return userDao.getUser(id);
    }
}

3、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.hua.saf" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}" />
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation"  value="classpath:sqlMapConfig.xml"/>
        <!-- 自动扫描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中单独指定xml文件-->
        <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
<?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 type="com.hua.saf.pojo.User" alias="User" />
    </typeAliases>
</configuration>
@Repository
public class UserDao extends SqlSessionDaoSupport{
    
    public User getUser(int id) {
        return this.getSqlSession().selectOne(this.getClass().getName() + ".getUser", 1);
    }
  //使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强
  //也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到少个,多个dao就很麻烦。
  //<bean id="userDao" class="com.hua.saf.dao.UserDao">
  //    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
  //</bean>
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        // TODO Auto-generated method stub
        super.setSqlSessionFactory(sqlSessionFactory);
    }
}
@Service
public class UserService{
    
    @Resource
    private UserDao userDao;
    
    public User getUserss(int id) {
        return userDao.getUser(1);
    }
}

There are no comment yet.

HTML tag cannot be used in this comment.