欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring 整合 mybatis 中數(shù)據(jù)源的幾種配置方式(總結(jié)篇)

 更新時間:2018年05月06日 16:22:29   作者:海小鑫  
因為spring 整合mybatis的過程中, 有好幾種整合方式,尤其是數(shù)據(jù)源那塊,經(jīng)??吹讲灰粯拥呐渲梅绞?,總感覺有點亂,所以今天有空總結(jié)下,感興趣的朋友跟隨腳本之家小編一起學習吧

因為spring 整合mybatis的過程中, 有好幾種整合方式,尤其是數(shù)據(jù)源那塊,經(jīng)??吹讲灰粯拥呐渲梅绞?,總感覺有點亂,所以今天有空總結(jié)下。

  一、采用org.mybatis.spring.mapper.MapperScannerConfigurer

  其實逆向工程也是這種方式

  1、數(shù)據(jù)源配配置文件

 2、DAO文件

 package com.jdd.mapper;
 import com.jdd.pojo.Employee;
 import java.util.List;
 public interface EmployeeMapper {
   public Employee getEmployeeById(int id);
   public List<Employee> findAllEmployees();
 }

  3、Mapper.xml 文件

   <?xml version="." encoding="UTF-" ?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper .//EN"
 "http://mybatis.org/dtd/mybatis--mapper.dtd">
 <mapper namespace="com.jdd.mapper.EmployeeMapper">
   <select id="getEmployeeById" parameterType="int" resultType="com.jdd.pojo.Employee">
     <![CDATA[
       select * from employee where id = #{id};
     ]]>
   </select>
   <select id="findAllEmployees" resultType="com.jdd.pojo.Employee">
     <![CDATA[
       select * from employee where status='';
     ]]>
   </select>
 </mapper>

   這樣在service類里就可以直接注入dao接口了

 package com.jdd.service.impl;
 import com.jdd.mapper.EmployeeMapper;
 import com.jdd.pojo.Employee;
 import com.jdd.service.EmployeeService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import java.util.List;
 @Service("employeeService")
 public class EmployeeServiceImpl implements EmployeeService{
   @Autowired
   private EmployeeMapper employeeMapper;
   @Override
   public Employee getEmployeeById(int id) {
     return employeeMapper.getEmployeeById(id);
   }
   @Override
   public List<Employee> findAllEmployees() {
     return employeeMapper.findAllEmployees();
   }
 }

    二、 采用抽象類org.mybatis.spring.support.SqlSessionDaoSupport, 給它注入 sqlSessionFactory的方式

  1、數(shù)據(jù)源配置文件

   <?xml version="." encoding="UTF-"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:xsi="http://www.w.org//XMLSchema-instance"
   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
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-..xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-..xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-..xsd">
   <!-- 加載配置文件 -->
   <context:property-placeholder location="classpath:resource/*.properties" />
   <!-- 數(shù)據(jù)庫連接池 -->
   <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="maxActive" value="" />
     <property name="minIdle" value="" />
   </bean>
   <!-- sqlsessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
     <property name="dataSource" ref="dataSource"></property>
     <property name="mapperLocations" value="classpath:com/jdd/mapper/*.xml"></property>
   </bean>
 </beans>

   2、baseDao類

 package com.jdd.dao;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.mybatis.spring.support.SqlSessionDaoSupport;
 import javax.annotation.Resource;
 public abstract class BaseDao extends SqlSessionDaoSupport {
   @Resource
   public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
     super.setSqlSessionFactory(sqlSessionFactory);
   }
 }

   3、接口 EmployeeDao.java 類

 package com.jdd.dao;
 import com.jdd.pojo.Employee;
 import java.util.List;
 public interface EmployeeDao {
   Employee getEmployeeById(int id);
   List<Employee> findAllEmployees();
 }

  4、dao實現(xiàn)類 EmployeeDaoImpl

 package com.jdd.dao.impl;
 import com.jdd.dao.BaseDao;
 import com.jdd.dao.EmployeeDao;
 import com.jdd.pojo.Employee;
 import org.springframework.stereotype.Repository;
 import java.util.List;
 @Repository("employeeDao")
 public class EmployeeDaoImpl extends BaseDao implements EmployeeDao {
   @Override
   public Employee getEmployeeById(int id) {
     return this.getSqlSession().selectOne("com.jdd.dao.EmployeeDao.getEmployeeById", id);
   }
   @Override
   public List<Employee> findAllEmployees() {
     return this.getSqlSession().selectList("com.jdd.dao.EmployeeDao.findAllEmployees");
   }
 }

  5、這樣就可以在service類里注入 employeeDao了

  三、采用 org.mybatis.spring.SqlSessionTemplate 模板類

  1、數(shù)據(jù)源文件

 <?xml version="." encoding="UTF-"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:xsi="http://www.w.org//XMLSchema-instance"
   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
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-..xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-..xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-..xsd">
   <!-- 加載配置文件 -->
   <context:property-placeholder location="classpath:resource/*.properties" />
   <!-- 數(shù)據(jù)庫連接池 -->
     <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="maxActive" value="" />
     <property name="minIdle" value="" />
   </bean>
   <!-- sqlsessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
     <property name="dataSource" ref="dataSource"></property>
     <property name="mapperLocations" value="classpath:com/jdd/mapper/*.xml"></property>
   </bean>
   <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg index="" ref="sqlSessionFactory"/>
   </bean>
 </beans>

  2、 basedao.java 類

 package com.jdd.dao;
 import org.mybatis.spring.SqlSessionTemplate;
 import javax.annotation.Resource;
 public abstract class BaseDao {
   public SqlSessionTemplate sqlSessionTemplate;
   @Resource
   public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
     this.sqlSessionTemplate = sqlSessionTemplate;
   }
 }

  3、接口 EmployeeDao.java 類  

package com.jdd.dao;
 import com.jdd.pojo.Employee;
 import java.util.List;
 public interface EmployeeDao {
   Employee getEmployeeById(int id);
   List<Employee> findAllEmployees();
 }

  4、dao實現(xiàn)類 EmployeeDaoImpl

 package com.jdd.dao.impl;
 import com.jdd.dao.BaseDao;
 import com.jdd.dao.EmployeeDao;
 import com.jdd.pojo.Employee;
 import org.springframework.stereotype.Repository;
 import java.util.List;
 @Repository("employeeDao")
 public class EmployeeDaoImpl extends BaseDao implements EmployeeDao {
   @Override
   public Employee getEmployeeById(int id) {
     return sqlSessionTemplate.selectOne("com.jdd.dao.EmployeeDao.getEmployeeById", id);
   }
   @Override
   public List<Employee> findAllEmployees() {
     return sqlSessionTemplate.selectList("com.jdd.dao.EmployeeDao.findAllEmployees");
   }
 }

  5、同樣現(xiàn)在也可以在service類里直接注入 employeeDao使用了。

  注:這里basedao的注入比較靈活,也可以注入 SqlSessionFactory, 然后再setter方法里創(chuàng)建 SqlSessionTemplate,如下:

 package com.jdd.dao;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.mybatis.spring.SqlSessionTemplate;
 import javax.annotation.Resource;
 public abstract class BaseDao {
   public SqlSessionTemplate sqlSessionTemplate;
   @Resource
   public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
     sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
   }
 }

  其實不管是采用 繼承SqlSessionDaoSupport類, 注入 sqlSessionFactory的方式, 還是直接注入 SqlSessionTemplate 的方式, 本質(zhì)上是一樣的。

  如果你采用 注入 sqlSessionFactory的方式, 它在底層也是通過sqlSessionFactory 來創(chuàng)建 SqlSessionTemplate ,然后通過其api來操作。

  不信給你們看下 SqlSessionDaoSupport 的源碼:

 //
 // Source code recreated from a .class file by IntelliJ IDEA
 // (powered by Fernflower decompiler)
 //
 package org.mybatis.spring.support;
 import org.apache.ibatis.session.SqlSession;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.mybatis.spring.SqlSessionTemplate;
 import org.springframework.dao.support.DaoSupport;
 import org.springframework.util.Assert;
 public abstract class SqlSessionDaoSupport extends DaoSupport {
   private SqlSession sqlSession;
   private boolean externalSqlSession;
   public SqlSessionDaoSupport() {
   }
   public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
     if (!this.externalSqlSession) {
       this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
     }
   }
   public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
     this.sqlSession = sqlSessionTemplate;
     this.externalSqlSession = true;
   }
   public SqlSession getSqlSession() {
     return this.sqlSession;
   }
   protected void checkDaoConfig() {
     Assert.notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
   }
 }

   同樣 SqlSessionTemplate 繼承了 SqlSession 接口, 因此不管操作哪個效果都一樣

 //
  // Source code recreated from a .class file by IntelliJ IDEA
  // (powered by Fernflower decompiler)
  //
  package org.mybatis.spring;
  import java.lang.reflect.InvocationHandler;
  import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.sql.Connection;
 import java.util.List;
 import java.util.Map;
 import org.apache.ibatis.exceptions.PersistenceException;
 import org.apache.ibatis.executor.BatchResult;
 import org.apache.ibatis.reflection.ExceptionUtil;
 import org.apache.ibatis.session.Configuration;
 import org.apache.ibatis.session.ExecutorType;
 import org.apache.ibatis.session.ResultHandler;
 import org.apache.ibatis.session.RowBounds;
 import org.apache.ibatis.session.SqlSession;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.springframework.dao.support.PersistenceExceptionTranslator;
 import org.springframework.util.Assert;
 public class SqlSessionTemplate implements SqlSession {
   private final SqlSessionFactory sqlSessionFactory;
   private final ExecutorType executorType;
   private final SqlSession sqlSessionProxy;
   private final PersistenceExceptionTranslator exceptionTranslator;
   public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
     this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
   }
   public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
     this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true));
   }
   public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) {
     Assert.notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");
     Assert.notNull(executorType, "Property 'executorType' is required");
     this.sqlSessionFactory = sqlSessionFactory;
     this.executorType = executorType;
     this.exceptionTranslator = exceptionTranslator;
     this.sqlSessionProxy = (SqlSession)Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[]{SqlSession.class}, new SqlSessionTemplate.SqlSessionInterceptor());
   }
   public SqlSessionFactory getSqlSessionFactory() {
     return this.sqlSessionFactory;
   }
   public ExecutorType getExecutorType() {
     return this.executorType;
   }
   public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
     return this.exceptionTranslator;
   }
   public <T> T selectOne(String statement) {
     return this.sqlSessionProxy.selectOne(statement);
   }
   public <T> T selectOne(String statement, Object parameter) {
     return this.sqlSessionProxy.selectOne(statement, parameter);
   }
   public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
     return this.sqlSessionProxy.selectMap(statement, mapKey);
   }
   public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
     return this.sqlSessionProxy.selectMap(statement, parameter, mapKey);
   }
   public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
     return this.sqlSessionProxy.selectMap(statement, parameter, mapKey, rowBounds);
   }
   public <E> List<E> selectList(String statement) {
     return this.sqlSessionProxy.selectList(statement);
   }
   public <E> List<E> selectList(String statement, Object parameter) {
     return this.sqlSessionProxy.selectList(statement, parameter);
   }
   public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
     return this.sqlSessionProxy.selectList(statement, parameter, rowBounds);
   }
   public void select(String statement, ResultHandler handler) {
     this.sqlSessionProxy.select(statement, handler);
   }
   public void select(String statement, Object parameter, ResultHandler handler) {
     this.sqlSessionProxy.select(statement, parameter, handler);
   }
   public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
     this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
   }
   public int insert(String statement) {
     return this.sqlSessionProxy.insert(statement);
   }
   public int insert(String statement, Object parameter) {
     return this.sqlSessionProxy.insert(statement, parameter);
   }
   public int update(String statement) {
     return this.sqlSessionProxy.update(statement);
   }
   public int update(String statement, Object parameter) {
     return this.sqlSessionProxy.update(statement, parameter);
   }
   public int delete(String statement) {
     return this.sqlSessionProxy.delete(statement);
   }
   public int delete(String statement, Object parameter) {
     return this.sqlSessionProxy.delete(statement, parameter);
   }
   public <T> T getMapper(Class<T> type) {
     return this.getConfiguration().getMapper(type, this);
   }
   public void commit() {
     throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
   }
   public void commit(boolean force) {
     throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
   }
   public void rollback() {
     throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
   }
   public void rollback(boolean force) {
     throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
   }
   public void close() {
     throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
   }
   public void clearCache() {
     this.sqlSessionProxy.clearCache();
   }
   public Configuration getConfiguration() {
     return this.sqlSessionFactory.getConfiguration();
   }
   public Connection getConnection() {
     return this.sqlSessionProxy.getConnection();
   }
   public List<BatchResult> flushStatements() {
     return this.sqlSessionProxy.flushStatements();
   }
   private class SqlSessionInterceptor implements InvocationHandler {
     private SqlSessionInterceptor() {
     }
     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       SqlSession sqlSession = SqlSessionUtils.getSqlSession(SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);
       Object unwrapped;
       try {
         Object result = method.invoke(sqlSession, args);
         if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
           sqlSession.commit(true);
         }
         unwrapped = result;
       } catch (Throwable var) {
         unwrapped = ExceptionUtil.unwrapThrowable(var);
         if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
           SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
           sqlSession = null;
           Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException)unwrapped);
           if (translated != null) {
             unwrapped = translated;
           }
         }
         throw (Throwable)unwrapped;
       } finally {
         if (sqlSession != null) {
           SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
         }
       }
       return unwrapped;
     }
   }
 }

總結(jié)

以上所述是小編給大家介紹的spring 整合 mybatis 中數(shù)據(jù)源的幾種配置方式,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

相關(guān)文章

  • 深入理解JAVA多線程之線程間的通信方式

    深入理解JAVA多線程之線程間的通信方式

    下面小編就為大家?guī)硪黄钊肜斫釰AVA多線程之線程間的通信方式。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-05-05
  • IDEA配置java開發(fā)環(huán)境(maven、gradle、tomcat)

    IDEA配置java開發(fā)環(huán)境(maven、gradle、tomcat)

    這篇文章主要介紹了IDEA配置java開發(fā)環(huán)境(maven、gradle、tomcat),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • Spring Boot應(yīng)用監(jiān)控的實戰(zhàn)教程

    Spring Boot應(yīng)用監(jiān)控的實戰(zhàn)教程

    Spring Boot 提供運行時的應(yīng)用監(jiān)控和管理功能,下面這篇文章主要給大家介紹了關(guān)于Spring Boot應(yīng)用監(jiān)控的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧
    2018-05-05
  • 微服務(wù)實戰(zhàn)之怎樣提升springboot服務(wù)吞吐量

    微服務(wù)實戰(zhàn)之怎樣提升springboot服務(wù)吞吐量

    這篇文章主要介紹了微服務(wù)實戰(zhàn)之怎樣提升springboot服務(wù)吞吐量方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • spring boot RestTemplate 發(fā)送get請求的踩坑及解決

    spring boot RestTemplate 發(fā)送get請求的踩坑及解決

    這篇文章主要介紹了spring boot RestTemplate 發(fā)送get請求的踩坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • SpringBoot實現(xiàn)分布式任務(wù)調(diào)度的詳細步驟

    SpringBoot實現(xiàn)分布式任務(wù)調(diào)度的詳細步驟

    隨著互聯(lián)網(wǎng)應(yīng)用的規(guī)模和復雜度不斷增加,單節(jié)點任務(wù)調(diào)度系統(tǒng)已經(jīng)難以滿足高并發(fā)、大數(shù)據(jù)量的處理需求,分布式任務(wù)調(diào)度成為了解決這一問題的重要手段,本文將介紹如何在Spring Boot中實現(xiàn)分布式任務(wù)調(diào)度,需要的朋友可以參考下
    2024-08-08
  • maven配置多個鏡像的實現(xiàn)方法

    maven配置多個鏡像的實現(xiàn)方法

    這篇文章主要介紹了maven配置多個鏡像的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-06-06
  • Springboot自動加載配置的原理解析

    Springboot自動加載配置的原理解析

    Springboot遵循“約定優(yōu)于配置”的原則,使用注解對一些常規(guī)的配置項做默認配置,減少或不使用xml配置,讓你的項目快速運行起來,這篇文章主要給大家介紹了關(guān)于Springboot自動加載配置原理的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • Spring?Security中使用authorizeRequests遇到的問題小結(jié)

    Spring?Security中使用authorizeRequests遇到的問題小結(jié)

    Spring?是非常流行和成功的?Java?應(yīng)用開發(fā)框架,Spring?Security?正是?Spring?家族中的成員,這篇文章主要介紹了Spring?Security中使用authorizeRequests遇到的問題,需要的朋友可以參考下
    2023-02-02
  • Spring?Boot?配置?Hikari?數(shù)據(jù)庫連接池的操作代碼

    Spring?Boot?配置?Hikari?數(shù)據(jù)庫連接池的操作代碼

    數(shù)據(jù)庫連接池是一個提高程序與數(shù)據(jù)庫的連接的優(yōu)化,連接池它主要作用是提高性能、節(jié)省資源、控制連接數(shù)、連接管理等操作,這篇文章主要介紹了SpringBoot配置Hikari數(shù)據(jù)庫連接池,需要的朋友可以參考下
    2023-09-09

最新評論