spring和mybatis的整合方式

1.Dao类继承org.mybatis.spring.support.SqlSessionDaoSupport

Spring配置文件

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
   <property name="dataSource" ref="dataSource" />  
   <property  name="configLocation"  value="classpath:sqlMapConfig.xml"/>  
 </bean>  
 <bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">   
      <constructor-arg index="0" ref="sqlSessionFactory" />   
</bean>  
<bean id="userDaoImpl" class="xx.yy.impl.UserDaoImpl">  
   <property name="sqlSessionTemplate" ref="sqlSession" />   
   <!--或者直接注入SqlSessionFactory实例,二者都指定时,SqlSessionFactory会失效 -->  
   <!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" />  
-->  
</bean>  

 

UserDaoImpl.java

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {     
  public User getUserById(User user) {     
     return (User) getSqlSession().selectOne("xx.yy.User.getUser", user);    
  }  
}

 

SqlSessionDaoSupport.java

/**
 *    Copyright 2010-2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.mybatis.spring.support;

import static org.springframework.util.Assert.notNull;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.DaoSupport;

/**
 * Convenient super class for MyBatis SqlSession data access objects.
 * It gives you access to the template which can then be used to execute SQL methods.
 * <p>
 * This class needs a SqlSessionTemplate or a SqlSessionFactory.
 * If both are set the SqlSessionFactory will be ignored.
 * <p>
 * {code Autowired} was removed from setSqlSessionTemplate and setSqlSessionFactory
 * in version 1.2.0.
 * 
 * @author Putthibong Boonbong
 *
 * @see #setSqlSessionFactory
 * @see #setSqlSessionTemplate
 * @see SqlSessionTemplate
 * @version $Id$
 */
public abstract class SqlSessionDaoSupport extends DaoSupport {

  private SqlSession sqlSession;

  private boolean externalSqlSession;

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    if (!this.externalSqlSession) {
      this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
    }
  }

  public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
    this.sqlSession = sqlSessionTemplate;
    this.externalSqlSession = true;
  }

  /**
   * Users should use this method to get a SqlSession to call its statement methods
   * This is SqlSession is managed by spring. Users should not commit/rollback/close it
   * because it will be automatically done.
   *
   * @return Spring managed thread safe SqlSession
   */
  public SqlSession getSqlSession() {
    return this.sqlSession;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void checkDaoConfig() {
    notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
  }

}

 

1>创建UserDaoImpl对象的时候,会调用父类中的setSqlSessionTemplate或者setSqlSessionFactory方法来注入sqlSession

2>UserDaoImpl的getUserById里面,直接调用getSqlSession()方法来获得之前注入的sqlSession对象

3>调用sqlSession的接口方法来执行具体的sql语句

2.不用继承SqlSessionDaoSupport,而是直接向Dao类中注入SqlSessionTemplate
(SqlSessionDaoSupport里面其实返回的就是SqlSessionTemplate对象)

UserDaoImpl.java

public class UserDaoImpl implements  UserDao  {  
   public SqlSessionTemplate sqlSession;  
   public User getUserById(User user) {  
       return (User)sqlSession.selectOne("com.xxt.ibatis.dbcp.domain.User.getUser", user);  
   }  
   public void setSqlSession(SqlSessionTemplate sqlSession) {  
        this.sqlSession = sqlSession;  
   }  
 }  

Spring配置文件

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
   <property name="dataSource" ref="dataSource" />  
   <property  name="configLocation"  value="classpath:sqlMapConfig.xml"/>  
</bean>  
<bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">   
      <constructor-arg index="0" ref="sqlSessionFactory" />   
</bean>  
<bean id="userDaoImpl" class="xx.yy.impl.UserDaoImpl">  
   <property name="sqlSession" ref="sqlSession" />    
</bean>  

 

1和2的整合方式差不太多,只是一个继承了SqlSessionDaoSupport,另一个直接注入SqlSessionTemplate

3.不直接使用SqlSession接口,而是使用org.mybatis.spring.mapper.MapperFactoryBean来自动生成映射器接口的代理实现,Dao里面直接调用Mapper接口来间接执行底层的sql语句

Spring配置文件

<!-- 引入jdbc配置文件 -->  
     <context:property-placeholder location="jdbc.properties"/>  
      <!--创建jdbc数据源 -->  
      <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}"/>  
      </bean>  
      <!-- 创建SqlSessionFactory,同时指定数据源-->  
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
      <property name="dataSource" ref="dataSource" />
<!-- 如果采用注解的方式将sql语句配置在Mapper接口的对应方法前面,configLocation不需要配置 -->
       <beans:property name="configLocation"  
           value="classpath:conf/mybatis-config.xml" />  
      </bean>  
      <!--创建数据映射器,数据映射器必须为接口-->  
      <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">   
          <property name="mapperInterface" value="xx.yy.dao.UserMapper" />  
          <property name="sqlSessionFactory" ref="sqlSessionFactory" />   
      </bean>  
      <bean id="userDaoImpl" class="xx.yy.dao.impl.UserDaoImpl">  
          <property name="userMapper" ref="userMapper"/>  
 </bean>  

UserMapper.java

public interface UserMapper {  
      @Select("SELECT * FROM user WHERE id = #{userId}")   
      User getUser(@Param("userId") long id);   
}  

UserDaoImpl.java

public class UserDaoImpl implements UserDao {  
       private UserMapper userMapper;  
       public void setUserMapper(UserMapper userMapper) {   
           this.userMapper = userMapper;   
       }   
       public User getUserById(User user) {  
          return userMapper.getUser(user.getId());   
       }  
}  

UserMapper.xml

<mapper namespace="xx.yy.dao.UserMapper">  
     <resultMap type="User" id="userMap">  
        <id property="id" column="id" />  
        <result property="name" column="name" />  
        <result property="password" column="password" />  
        <result property="createTime" column="createtime" />  
     </resultMap>  
     <select id="getUser" parameterType="User" resultMap="userMap">  
       select * from user where id = #{id}  
     </select>  
<mapper/>  
4.如果Mapper接口比较多的时候,3.的spring配置文件里面要分别对每一个mapper增加配置,为了简化配置,可以使用org.mybatis.spring.mapper.MapperScannerConfigurer来自动扫描所有的mapper接口,并自动生成相应的mapper代理对象

spring配置文件

<!-- 引入jdbc配置文件 -->  
     <context:property-placeholder location="jdbc.properties"/>  
      <!--创建jdbc数据源 -->  
      <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}"/>  
      </bean>  
      <!-- 创建SqlSessionFactory,同时指定数据源-->  
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
      <property name="dataSource" ref="dataSource" />
<!-- 如果采用注解的方式将sql语句配置在Mapper接口的对应方法前面,configLocation不需要配置 -->
       <beans:property name="configLocation"  
           value="classpath:conf/mybatis-config.xml" />  
      </bean>  
      <!--配置扫描器-->  
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">   
          <property name="basePackage" value="xx.yy.dao" />  
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />   
      </bean>  
 </bean>  

当然如果业务逻辑比较简单的话,可以在service类里面直接注入Mapper接口进行dao操作,也可以单独设计一层dao层,然后将mapper接口注入到dao类里面进行使用.

1,2直接面对的是SqlSession接口,而3,4根据mapper接口自动生成代理实现类,增加了mapper层,使我们直接面对mapper接口层进行dao操作,从而不用关注底层的SqlSession接口

猜你喜欢

转载自blogzhoubo.iteye.com/blog/2359277