MyBatis Initial Learning (Spring Integrates MyBatis)

Keywords: Mybatis Spring Session xml

Be careful:

1) Make sure to integrate the two and MyBatis-Spring versions, which often fail to run after completion because of version incompatibility.

2) Because annotation configuration is more convenient, my project uses annotation to configure transactions and inject bean s.

3) This article only provides some configuration references for the integration section. For the specific use of Spring and MyBatis, please refer to other blog posts.


In native MyBatis, the task of manipulating the database ultimately falls to sqlSession or the corresponding Mapper interface. Ultimately, both approaches require SqlSession Factory. So when using Spring to integrate MyBatis, the key is also to get Sqlsession Factory.

And Spring configures transactions in your usual way. @ Transactional annotations and AOP-style configurations are supported. During transaction processing, a single SqlSession object will be created and used. When the transaction is completed, the session is submitted or rolled back in an appropriate manner. So you only need to pay attention to your business code without paying attention to details such as transaction submission, rollback, etc.


Spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p"
	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">
	<!-- Scanned@component @controller @service Class packages of bean within -->
	<context:component-scan base-package="com.paditang.dao"/>
	<context:component-scan base-package="com.paditang.service"/>
	
	  
	<!-- Load spring Resource files in -->
	 <context:property-placeholder location="classpath:jdbc.properties" />
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"	
		p:driverClassName="net.sourceforge.jtds.jdbc.Driver"
		p:url="jdbc:jtds:sqlserver://localhost:1433;DatabaseName=test_api"
		p:username="sa"
		p:password="password">
	</bean>
		
	<!-- Obtain MyBatis sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="dataSource"
		p:configLocation="classpath:MyBatis-conf.xml"
		p:mapperLocations="classpath:com/paditang/mapping/*.xml"><!-- scanning Mapper file -->
	</bean>
	
	<!-- Use the provided template -->
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory"></constructor-arg>
	</bean>
	
	<!-- Scanning for direct use mapper Interface class operations dao -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
		p:sqlSessionFactory-ref="sqlSessionFactory"
		p:basePackage="com.paditang.mapping">
		
	</bean>
	
	<!-- Configuring Transaction Manager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

	<!-- Configuring annotation-based declarative transactions -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	
</beans>

MyBatis configuration:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  
   <!-- Use Log4j Journal -->
  <settings>
  		<setting name="lazyLoadingEnabled" value="false"/>
		<setting name="logImpl" value="LOG4J"></setting>
  </settings>
  
  <!-- Aliases, which can be configured to replace full qualified names -->
  <typeAliases>
  	<typeAlias alias="User" type="com.paditang.domain.User"/>
  </typeAliases>
  <!-- stay Spring Do not add maps here after configuration scan
  <mappers>
    <mapper resource="com/paditang/mapping/UserMapper.xml"/>
  </mappers> -->
</configuration>

Example code:

package com.paditang.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.paditang.domain.User;
import com.paditang.mapping.UserMapper;

@Repository
public class UserDao {

	@Autowired
	private UserMapper userMapper;
	
	public User getUserById(int id){
		return userMapper.getUser(id);
	}
	public String getLocationByUserName(String name){
		return userMapper.getLocationByUserName(name);
	}
}


Native API s can also be used:

public class UserMapperSqlSessionImpl implements UserMapper {
  // SqlSessionFactory would normally be set by SqlSessionDaoSupport
  private SqlSessionFactory sqlSessionFactory;

  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
  }

  public User getUser(String userId) {
    // note standard MyBatis API usage - opening and closing the session manually
    SqlSession session = sqlSessionFactory.openSession();

    try {
      return (User) session.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
    } finally {
      session.close();
    }
  }
}

Note:

Use this option carefully, because incorrect use can lead to runtime errors or worse data consistency problems. These are warnings:

1) It will not be involved in Spring's affairs.

2) If SqlSession uses DataSource, it will also be used by Spring Transaction Manager, and this code throws an exception when a transaction is currently in progress.

3) MyBatis's Default SqlSession is thread insecure. If it is injected into the bean, an error occurs.

4) Mappers created using DefaultSqlSession are not thread-safe either. If you inject them into bean s, there will be errors.

5) You must ensure that SqlSession is closed in the final block.


Personal source: https://github.com/caiwuxin/MyBatis Learning/tree/master/Spring-MyBatis

Reference: http://www.mybatis.org/spring/zh/index.html

Posted by tpl41803 on Sat, 20 Apr 2019 13:09:33 -0700