Integration of spring and mybatis

1.Dao class inherits org.mybatis.spring.support.SqlSessionDaoSupport

 

Spring configuration file

 

<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" />   
   <!--Or directly inject the SqlSessionFactory instance, when both are specified, the SqlSessionFactory will fail-->  
   <!-- <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> When the UserDaoImpl object is created, the setSqlSessionTemplate or setSqlSessionFactory method in the parent class will be called to inject the sqlSession

2> In the getUserById of UserDaoImpl, directly call the getSqlSession() method to obtain the previously injected sqlSession object

3> Call the interface method of sqlSession to execute the specific sql statement

 

2. Instead of inheriting SqlSessionDaoSupport, inject SqlSessionTemplate directly into the Dao class
( What SqlSessionDaoSupport actually returns is the SqlSessionTemplate object )

 

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 configuration file

 

<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>  

 

 

The integration methods of 1 and 2 are not too different, except that one inherits SqlSessionDaoSupport and the other directly injects SqlSessionTemplate

 

3. Instead of using the SqlSession interface directly, use org.mybatis.spring.mapper.MapperFactoryBean to automatically generate the proxy implementation of the mapper interface, and directly call the Mapper interface in Dao to indirectly execute the underlying sql statement

 

Spring configuration file

 

<!-- Introduce jdbc configuration file-->  
     <context:property-placeholder location="jdbc.properties"/>  
      <!--Create jdbc data source-->  
      <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>  
      <!-- Create SqlSessionFactory and specify data source -->  
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
      <property name="dataSource" ref="dataSource" />
<!-- If the sql statement is configured in front of the corresponding method of the Mapper interface by way of annotation, configLocation does not need to be configured-->
       <beans:property name="configLocation"  
           value="classpath:conf/mybatis-config.xml" />  
      </bean>  
      <!--Create a data mapper, the data mapper must be an interface-->  
      <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. If there are many Mapper interfaces, 3. In the spring configuration file, you need to add configuration to each mapper. In order to simplify the configuration, you can use org.mybatis.spring.mapper.MapperScannerConfigurer to automatically scan all mapper interfaces, and Automatically generate the corresponding mapper proxy object

 

spring configuration file

<!-- Introduce jdbc configuration file-->  
     <context:property-placeholder location="jdbc.properties"/>  
      <!--Create jdbc data source-->  
      <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>  
      <!-- Create SqlSessionFactory and specify data source -->  
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
      <property name="dataSource" ref="dataSource" />
<!-- If the sql statement is configured in front of the corresponding method of the Mapper interface by way of annotation, configLocation does not need to be configured-->
       <beans:property name="configLocation"  
           value="classpath:conf/mybatis-config.xml" />  
      </bean>  
      <!--Configure Scanner-->  
      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">   
          <property name="basePackage" value="xx.yy.dao" />  
          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />   
      </bean>  
 </bean>  

 

Of course, if the business logic is relatively simple, you can directly inject the Mapper interface into the service class for dao operations, or you can design a separate dao layer, and then inject the mapper interface into the dao class for use.

 

1 and 2 directly face the SqlSession interface, while 3 and 4 automatically generate the proxy implementation class according to the mapper interface, and add the mapper layer, so that we can directly face the mapper interface layer for dao operations, so we don't need to pay attention to the underlying SqlSession interface.

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326397662&siteId=291194637