1. 程式人生 > >Spring-Mybatis --- 配置SqlSessionFactoryBean,整合Spring-Mybatis 轉載 https://www.cnblogs.com/ClassNotF

Spring-Mybatis --- 配置SqlSessionFactoryBean,整合Spring-Mybatis 轉載 https://www.cnblogs.com/ClassNotF

 要利用Mybatis首先是需要匯入mybatis-x.x.x.jar,其次,要整合Spring和Mybatis需要匯入mybatis-spring-x.x.x.jar。

  JAR : mybatis-x.x.x

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.6</version>
        </
dependency>

  JAR : mybatis-spring-x.x.x

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>

1、Spring整合Mybatis的xml配置

  xml : POM

複製程式碼
        <!--
DB --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.apache.tomcat</
groupId> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.54</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>7.0.23</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency>
複製程式碼

  xml : DataSource

複製程式碼
    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
        <property name="poolProperties">
            <bean class="org.apache.tomcat.jdbc.pool.PoolProperties">
                <property name="driverClassName" value="com.mysql.jdbc.Driver" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.user}" />
                <property name="password" value="${jdbc.password}" />
                <!-- Register the pool with JMX. In order for the connection pool object to create the MBean. -->
                <property name="jmxEnabled" value="true" />
                <!-- The indication of whether objects will be validated by the idle object evictor. -->
                <property name="testWhileIdle" value="true" />
                <!-- The indication of whether objects will be validated before being borrowed from the pool. -->
                <property name="testOnBorrow" value="false" />
                <property name="testOnReturn" value="false" />
                <property name="initialSize" value="${jdbc.initialPoolSize}" />
                <property name="maxActive" value="${jdbc.maxActive}" />
                <property name="maxWait" value="${jdbc.maxWait}" />
                <property name="minIdle" value="${jdbc.minIdle}" />
                <property name="maxIdle" value="${jdbc.maxIdle}" />
                <property name="maxAge" value="60000" />
                <!-- The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. -->
                <property name="timeBetweenEvictionRunsMillis" value="15000" />
                <!-- The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. -->
                <property name="minEvictableIdleTimeMillis" value="60000" />
                <property name="removeAbandoned" value="true" />
                <property name="removeAbandonedTimeout" value="30" />
                <property name="validationQuery" value="SELECT 1" />
                <property name="validationInterval" value="30000" />
            </bean>
        </property>
    </bean>
複製程式碼

常用配置:

(如果在mybatis-config.xml利用<mappers>進行xml對映檔案的配置,就可以不用配置下面的mapperLocation屬性了)

複製程式碼
<!-- mybatis檔案配置,掃描所有mapper檔案 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
      p:dataSource-ref="dataSource"
      p:configLocation="classpath:mybatis-config.xml"
      p:mapperLocations="classpath:com/eliteams/quick4j/web/dao/*.xml"/>

<!-- spring與mybatis整合配置,掃描所有dao,在單資料來源的情況下可以不寫sqlSessionFactoryBeanName -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
      p:basePackage="com.eliteams.quick4j.web.dao"
      p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
複製程式碼

-------------------------阿彌陀佛----佛祖保佑----永無BUG--------------------------

2、Spring和Mybatis整合的三種方式

  • SqlSessionFactoryBean來替代SqlSessionFactoryBuilder來建立SqlSession

  • 利用mybatis對映檔案**.xml來配置

    SqlSessionFactoryBean有一個必須屬性dataSource,另外其還有一個通用屬性configLocation(用來指定mybatis的xml配置檔案路徑)。

Spring的xml配置:

      <!-- 建立SqlSessionFactory,同時指定資料來源-->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          <property name="dataSource" ref="dataSource" /> 
          <!-- 指定sqlMapConfig總配置檔案,訂製的environment在spring容器中不在生效-->
          <property  name="configLocation"  value="classpath:sqlMapConfig.xml"/>
      </bean>

mybatis總配置檔案sqlMapConfig.xml:

複製程式碼
<configuration>
  <typeAliases>
     <typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" />
  </typeAliases>
  <mappers>
     <mapper resource="com/xxt/ibatis/dbcp/domain/userMapper.xml" />
  </mappers>
</configuration>
複製程式碼

userMapper.xml:

複製程式碼
<mapper namespace="com.xxt.ibatis.dbcp.dao.UserDao">
     <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="getUserById" parameterType="int" resultMap="userMap">
       select * from user where id = #{id}
     </select>
<mapper/>
複製程式碼

DAO層介面類UserDao.java:注意此處定義的介面方法需要和UserMapper.xml對映的<select>標籤的id對應

public interface UserDao {
    public User getUserById(int id);
}

需要操作資料時呼叫的類UserService.java:

複製程式碼
public class UserService {
     //此處省略sqlSession的獲取方法
     private SqlSession sqlSession;
     private UserDao userDao;
     public User getUserById(int id) {
         return userDao.getUserById(id);
     }
}
複製程式碼

  • SqlSessionFactoryBean來替代SqlSessionFactoryBuilder來建立SqlSession

  • 採用資料對映器(MapperFactoryBean)的方式

  • 不用寫mybatis對映檔案

  • 採用註解方式提供相應的sql語句和輸入引數。

Spring的xml配置:

複製程式碼
     <!-- 引入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" /> 
      </bean>

      <!--建立資料對映器,資料對映器必須為介面-->
      <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
          <property name="mapperInterface" value="com.xxt.ibatis.dbcp.dao.UserMapper" />
          <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
      </bean>

      <bean id="userDaoImpl" class="com.xxt.ibatis.dbcp.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); 
}

DAO介面類UserDao.java:

public interface UserDao {
       public User getUserById(User user);
}

DAO介面實現類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()); 
       }
}
複製程式碼

  • SqlSessionFactoryBean來替代SqlSessionFactoryBuilder建立SqlSession

  • 不採用採用資料對映器(MapperFactoryBean)的方式,改為MapperScannerConfigurer 進行掃描

  • 不用寫mybatis對映檔案

  • 採用註解方式提供相應的sql語句和輸入引數。

  • 採用註解方式省去定義mapper的Bean

    MapperFactoryBean 建立的代理類實現了 UserMapper 介面,並且注入到應用程式中。 因為代理建立在執行時環境中(Runtime,譯者注) ,那麼指定的對映器必須是一個介面,而 不是一個具體的實現類。

    上面的MapperFactoryBean配置有一個很大的缺點,就是系統有很多的配置檔案時 全部需要手動編寫,所以上述的方式已經不用了。

    沒有必要在 Spring 的 XML 配置檔案中註冊所有的對映器。相反,你可以使用一個 MapperScannerConfigurer , 它將會查詢類路徑下的對映器並自動將它們建立成MapperFactoryBean。

Spring的xml配置:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="org.mybatis.spring.sample.mapper" />
</bean>

    basePackage 屬性是讓你為對映器介面檔案設定基本的包路徑。 你可以使用分號或逗號 作為分隔符設定多於一個的包路徑。每個對映器將會在指定的包路徑中遞迴地被搜尋到。

    注 意 , 沒有必要去指定SqlSessionFactory 或 SqlSessionTemplate , 因為 MapperScannerConfigurer 將會建立MapperFactoryBean,之後自動裝配。但是,如果你使 用了一個 以上的 DataSource,那 麼自動裝配可能會失效 。這種情況下 ,你可以使用 sqlSessionFactoryBeanName 或 sqlSessionTemplateBeanName 屬性來設定正確的 bean 名稱來使用。

啦啦啦

啦啦啦

啦啦啦