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

spring-mybatis與原生mybatis使用對(duì)比分析

 更新時(shí)間:2017年11月20日 15:09:00   投稿:mrr  
這篇文章主要介紹了spring-mybatis與原生mybatis使用對(duì)比分析,需要的朋友可以參考下

原生mybatis使用方法:

String resource = "mybatis-config.xml"; 
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
SqlSession session = sqlSessionFactory.openSession();  
try {   
      Employee employee = new Employee(null, "doubi", "1", "ddd@sys.com"); 
      EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);   
      mapper.addEmp(employee);        
      session.commit();  
} finally {
   session.close();  
}

spring使用方法,直接注入即可

@Autowired
EmployeeMapper employeeMapper

那么spring為我們做了什么?下面研究一下mybatis-spring.jar這個(gè)jar包

首先來看一下如何使用spring整合mybatis,下面是使用spring-mybatis的四種方法:

方法一:(使用MapperFactoryBean)

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>    
  <property name="configLocation" value="classpath:mybatis-config.xml"></property>    
  <!-- 自動(dòng)掃描mapping.xml文件 -->    
  <property name="mapperLocations" value="classpath:mapper/*.xml"></property>  
</bean>
<!--上面生成sqlSessionFactory的幾個(gè)方法基本相同-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
 <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
 <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

這樣做的缺點(diǎn)是每一個(gè)mapper接口都要在xml里配置一下

方法二:采用接口org.apache.ibatis.session.SqlSession的實(shí)現(xiàn)類 org.mybatis.spring.SqlSessionTemplate

mybatis中, sessionFactory可由SqlSessionFactoryBuilder.來創(chuàng)建。MyBatis-Spring 中,使用了SqlSessionFactoryBean來替代。SqlSessionFactoryBean有一個(gè)必須屬性dataSource,另外其還有一個(gè)通用屬性configLocation(用來指定mybatis的xml配置文件路徑)。

SqlSessionFactoryBean即相當(dāng)于原生mybatis中的SqlSessionFactoryBuilder

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  <property name="dataSource" ref="dataSource" />    
  <property name="configLocation" value="classpath:sqlMapConfig.xml"/>    
  <!-- 自動(dòng)掃描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中單獨(dú)指定xml文件-->    
  <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />  
</bean>    
<!-- mybatis spring sqlSessionTemplate,使用時(shí)直接讓spring注入即可 -->  
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">    
  <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>  
</bean>
//使用方法:
@Repositorypublic class UserDao{  @Resource  private SqlSessionTemplate sqlSessionTemplate;    public User getUser(int id) {    return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1);  }  }

為什么可以這樣寫,來看一下SqlSessionTemplate

public class SqlSessionTemplate implements SqlSession { private final SqlSessionFactory sqlSessionFactory; private final ExecutorType executorType; private final SqlSession sqlSessionProxy; private final PersistenceExceptionTranslator exceptionTranslator; /**  * Constructs a Spring managed SqlSession with the {@code SqlSessionFactory}  * provided as an argument.  *  * @param sqlSessionFactory  */ public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {  this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); }
........省略......
  public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,   PersistenceExceptionTranslator exceptionTranslator) {  notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");  notNull(executorType, "Property 'executorType' is required");  this.sqlSessionFactory = sqlSessionFactory;  this.executorType = executorType;  this.exceptionTranslator = exceptionTranslator;  this.sqlSessionProxy = (SqlSession) newProxyInstance(    SqlSessionFactory.class.getClassLoader(),    new Class[] { SqlSession.class },    new SqlSessionInterceptor()); }
}

如上面代碼所示,SqlSessionTemplate類實(shí)現(xiàn)了原生Mybatis中的SqlSession接口,實(shí)際上它就是原生mybatis中的SqlSession

方法三:采用抽象類 org.mybatis.spring.support.SqlSessionDaoSupport 提供SqlSession

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    <!-- 自動(dòng)掃描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中單獨(dú)指定xml文件-->
    <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
  </bean>
public class BaseDao extends SqlSessionDaoSupport{ //使用sqlSessionFactory @Autowired  private SqlSessionFactory sqlSessionFactory;  
@Autowired  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) 
{ 
super.setSqlSessionFactory(sqlSessionFactory);  
}  /**  * 執(zhí)行insert操作  * @param statement  * @return  */ public int insert(String statement) { 
return getSqlSession().insert(statement); } /**  * 執(zhí)行insert操作  * @param statement  * @param parameter  * @return  */ public int insert(String statement, Object parameter) {  
return getSqlSession().insert(statement, parameter); } 
public int update(String statement)
{  return getSqlSession().update(statement);
}
public int update(String statement, Object parameter) {  return getSqlSession().update(statement, parameter); } 
public int delete(String statement)
{  
return getSqlSession().delete(statement); 
} 
public int delete(String statement, Object parameter) { 
return getSqlSession().delete(statement, parameter); }  /**  * 獲取一個(gè)list集合  * @param statement  * @return  */ public List<?> selectList(String statement) {  return getSqlSession().selectList(statement); }  /**  * 根據(jù)參數(shù) 獲取一個(gè)list集合  * @param statement  * @param parameter  * @return  */ public List<?> selectList(String statement, Object parameter) {  return getSqlSession().selectList(statement, parameter); }  public Map<?, ?> selectMap(String statement, String mapKey) {  return getSqlSession().selectMap(statement, mapKey); } public Map<?, ?> selectMap(String statement, Object parameter, String mapKey) {  return getSqlSession().selectMap(statement, parameter, mapKey); }  /**  * 獲取Object對(duì)象  * @param statement  * @return  */ public Object selectOne(String statement) {  return getSqlSession().selectOne(statement); }  /**  * 獲取connection, 以便執(zhí)行較為復(fù)雜的用法  * @return  */ public Connection getConnection() {  return getSqlSession().getConnection(); } }

如上代碼,一個(gè)Dao類繼承了SqlSessionDaoSupport類后,就可以在類中注入SessionFact
ory,進(jìn)而通過getSqlSession()獲取當(dāng)前SqlSession

下面是 SqlSessionDaoSupport的源碼 ,它是一個(gè)抽象類,并擁有sqlSession屬性,在setSqlSessionFactory方法中實(shí)例化了該sqlSession:

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; 
} 
public SqlSession getSqlSession() 
{ 
return this.sqlSession; 
} 
protected void checkDaoConfig() 
{ 
notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required"); }}

方法四:(也是 最常見的使用方法 ,使用MapperScannerConfigurer,它將會(huì)查找類路徑下的映射器并自動(dòng)將它們創(chuàng)建成MapperFactoryBean)

由于直接使用MapperFactoryBean會(huì)在配置文件中配置大量mapper,因此這里使用包掃描的方式通過注解獲取該bean

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!-- 自動(dòng)掃描mapping.xml文件,**表示迭代查找 -->
    <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" />
  </bean>
  <!-- DAO接口所在包名,Spring會(huì)自動(dòng)查找其下的類 ,包下的類需要使用@MapperScan注解,否則容器注入會(huì)失敗 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.hua.saf.*" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
  </bean>
//使用如下代碼,即可完成注入
@Resource
private UserDao userDao;

下面看一下MapperScannerConfigurer這個(gè)類:

public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware { private String basePackage; private boolean addToConfig = true; private SqlSessionFactory sqlSessionFactory; private SqlSessionTemplate sqlSessionTemplate; private String sqlSessionFactoryBeanName; private String sqlSessionTemplateBeanName; private Class<? extends Annotation> annotationClass; private Class<?> markerInterface; private ApplicationContext applicationContext; private String beanName; private boolean processPropertyPlaceHolders; private BeanNameGenerator nameGenerator;
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {  if (this.processPropertyPlaceHolders) {   processPropertyPlaceHolders();  }  ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);  scanner.setAddToConfig(this.addToConfig);  scanner.setAnnotationClass(this.annotationClass);  scanner.setMarkerInterface(this.markerInterface);  scanner.setSqlSessionFactory(this.sqlSessionFactory);  scanner.setSqlSessionTemplate(this.sqlSessionTemplate);  scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);  scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);  scanner.setResourceLoader(this.applicationContext);  scanner.setBeanNameGenerator(this.nameGenerator);  scanner.registerFilters();  scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)); }
ClassPathMapperScanner :
public Set<BeanDefinitionHolder> doScan(String... basePackages) {  Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);  if (beanDefinitions.isEmpty()) {   logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");  } else {   for (BeanDefinitionHolder holder : beanDefinitions) {    GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();    if (logger.isDebugEnabled()) {     logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()        + "' and '" + definition.getBeanClassName() + "' mapperInterface");    }    // the mapper interface is the original class of the bean    // but, the actual class of the bean is MapperFactoryBean    definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());    definition.setBeanClass(MapperFactoryBean.class);    definition.getPropertyValues().add("addToConfig", this.addToConfig);    boolean explicitFactoryUsed = false;    if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {     definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));     explicitFactoryUsed = true;    } else if (this.sqlSessionFactory != null) {     definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);     explicitFactoryUsed = true;    }    if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {     if (explicitFactoryUsed) {      logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");     }     definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));     explicitFactoryUsed = true;    } else if (this.sqlSessionTemplate != null) {     if (explicitFactoryUsed) {      logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");     }     definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);     explicitFactoryUsed = true;    }    if (!explicitFactoryUsed) {     if (logger.isDebugEnabled()) {      logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");     }     definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);    }   }  }  return beanDefinitions; }

總結(jié):spring-mybatis與原生Mybatis相比,如下概念:

1)SqlSessionFactory類在兩者中都存在

2)前者用SqlSessionFactoryBean生成SqlSessionFactory,后者則使用SqlSessionFactoryBuilder;

3)前者使用SqlSessionTemplate,后者使用SqlSession,實(shí)際上前者實(shí)現(xiàn)了后者

4)MapperFactoryBean中實(shí)現(xiàn)了原生mybatis中下面的步驟,因此通過該類可以直接獲取到一個(gè)mapper接口的實(shí)現(xiàn)對(duì)象

EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);

總結(jié)

以上所述是小編給大家介紹的spring-mybatis與原生mybatis使用對(duì)比分析,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 超詳細(xì)的IntelliJ IDEA的安裝及配置

    超詳細(xì)的IntelliJ IDEA的安裝及配置

    這篇文章主要介紹了超詳細(xì)的IntelliJ IDEA的安裝及配置,文中有非常詳細(xì)的圖文示例,對(duì)想要安裝IDEA的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • 如何基于SpringSecurity的@PreAuthorize實(shí)現(xiàn)自定義權(quán)限校驗(yàn)方法

    如何基于SpringSecurity的@PreAuthorize實(shí)現(xiàn)自定義權(quán)限校驗(yàn)方法

    spring Security提供有若干個(gè)過濾器,它們能夠攔截Servlet請(qǐng)求,并將這些請(qǐng)求轉(zhuǎn)給認(rèn)證和訪問決策管理器處理,從而增強(qiáng)安全性,下面這篇文章主要給大家介紹了關(guān)于如何基于SpringSecurity的@PreAuthorize實(shí)現(xiàn)自定義權(quán)限校驗(yàn)方法的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • 分析ZooKeeper分布式鎖的實(shí)現(xiàn)

    分析ZooKeeper分布式鎖的實(shí)現(xiàn)

    在分布式的情況下,sychornized 和 Lock 已經(jīng)不能滿足我們的要求了,那么就需要使用第三方的鎖了,這里我們就使用 ZooKeeper 來實(shí)現(xiàn)一個(gè)分布式鎖
    2021-06-06
  • SpringBoot整合log4j2日志的實(shí)現(xiàn)

    SpringBoot整合log4j2日志的實(shí)現(xiàn)

    在項(xiàng)目推進(jìn)中,如果說第一件事是搭Spring框架的話,那么第二件事情就是在Sring基礎(chǔ)上搭建日志框架,大家都知道日志對(duì)于一個(gè)項(xiàng)目的重要性,尤其是線上Web項(xiàng)目,因?yàn)槿罩究赡苁俏覀兞私鈶?yīng)用如何執(zhí)行的唯一方式。此篇文章是博主在實(shí)踐中用Springboot整合log4j2日志的總結(jié)
    2021-06-06
  • 帶大家深入了解Spring事務(wù)

    帶大家深入了解Spring事務(wù)

    Spring框架提供統(tǒng)一的事務(wù)抽象,通過統(tǒng)一的編程模型使得應(yīng)用程序可以很容易地在不同的事務(wù)框架之間進(jìn)行切換. 在學(xué)習(xí)Spring事務(wù)前,我們先對(duì)數(shù)據(jù)庫(kù)事務(wù)進(jìn)行簡(jiǎn)單的介紹。,需要的朋友可以參考下
    2021-05-05
  • java中String的常見用法總結(jié)

    java中String的常見用法總結(jié)

    以下是關(guān)于string的七種用法,注意哦,記得要時(shí)常去查看java的API文檔,那個(gè)里面也有很詳細(xì)的介紹
    2013-10-10
  • MyBatis Mapper接受參數(shù)的四種方式代碼解析

    MyBatis Mapper接受參數(shù)的四種方式代碼解析

    這篇文章主要介紹了MyBatis Mapper接受參數(shù)的四種方式代碼解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • springboot連接多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法

    springboot連接多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法

    有時(shí)候一個(gè)SpringBoot項(xiàng)目需要同時(shí)連接兩個(gè)數(shù)據(jù)庫(kù),本文就來介紹一下springboot連接多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-08-08
  • @JsonSerialize(using = LongToStringUtil.class)注解的使用方式

    @JsonSerialize(using = LongToStringUtil.class)注解的使

    這篇文章主要介紹了@JsonSerialize(using = LongToStringUtil.class)注解的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Java反射如何修改private final成員變量值

    Java反射如何修改private final成員變量值

    這篇文章主要介紹了Java反射如何修改private final成員變量值,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07

最新評(píng)論