I'm going to teach you MyBatis, Quick Start collection.

Source: Internet
Author: User
Tags aop pack

Import Dependency Pack

With the knowledge of MyBatis, let's now explain how to integrate with spring. MyBatis and spring's integration work was done by the MyBatis team. So let's first introduce MyBatis and spring's integrated dependency pack. Here I'm using Gradle, and if you use a different build tool, change the following statement to the appropriate one.

Compile group: ' Org.mybatis ', Name: ' Mybatis-spring ', version: ' 1.3.1 '

Declaring a spring Bean

The integration package contains the Org.mybatis.spring.SqlSessionFactoryBean class, which is a factory class that makes it easy to create MyBatis sqlsessionfactory. All properties can be set through this class. If you want to use a traditional XML configuration, you can also set the Configlocation property to the MyBatis configuration file directly.

<!--the sqlsessionfactory--> of MyBatis

<bean id= "Sqlsessionfactory"

class= "Org.mybatis.spring.SqlSessionFactoryBean" >

<property name= "DataSource" ref= "DataSource"/>

<property name= "configlocation" value= "Configuration.xml"/>


<!--data source-->

<bean id= "DataSource"

class= "Com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource" >

<property name= "User" value= "root"/>

<property name= "Password" value= "12345678"/>

<property name= "url" value= "Jdbc:mysql://localhost:3306/test"/>

<property name= "UseSSL" value= "false"/>



Transaction management

MyBatis is a lightweight framework that does not have its own transaction manager. We can use the JDBC transaction manager directly. Other locations are similar to other transaction configuration methods, and are not described in detail.

<!--mybatis transaction manager using JDBC-->

<bean id= "TransactionManager"

class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >

<property name= "DataSource" ref= "DataSource"/>


<tx:advice id= "Txadvice"

Transaction-manager= "TransactionManager" >


<tx:method name= "get*" read-only= "true"/>

<tx:method name= "*"/>



<!--use AOP to set up transaction management-->


<aop:pointcut id= "DAO"

expression= "Execution (* yitian.study.dao.*.* (..))" />

<aop:advisor advice-ref= "Txadvice" pointcut-ref= "DAO"/>


Using sqlsession

MyBatis also provides a mybatistemplate class that will be sqlsession to spring management. We simply declare the object and inject it into the code.

<!--MyBatis sqlsession template that encapsulates sqlsession-->

<bean id= "Sqlsessiontemplate"

class= "Org.mybatis.spring.SqlSessionTemplate" >

<constructor-arg type= "Org.apache.ibatis.session.SqlSessionFactory"

ref= "Sqlsessionfactory"/>


Java Please click here to enter a picture description

Alternatively, you can inherit the Sqlsessiondaosupport class, which provides a getsqlsession () method that can directly capture the sqlsession currently managed by spring.

Injection Mapper

The MyBatis Mapper can be registered by the Mapperfactorybean factory class. After registering, we can inject directly into the DAO to use, even mybatistemplate is free.

<bean id= "Usermapper" class= "Org.mybatis.spring.mapper.MapperFactoryBean" >

<property name= "Mapperinterface" value= "Org.mybatis.spring.sample.mapper.UserMapper"/>

<property name= "Sqlsessionfactory" ref= "Sqlsessionfactory"/>


If there are multiple mapper, we can even use the namespace provided by MyBatis to scan all the mapper directly.

<!--automatic search mapper-->

<mybatis:scan base-package= "Yitian.study.mapper"/>

Then our code becomes very clean.


public class Authordaoimpl implements Authordao {

private sqlsessiontemplate template;

Private Multimapper Mapper;


Public Authordaoimpl (sqlsessiontemplate template, Multimapper mapper) {

This.template = template;//Template object is not even used

This.mapper = mapper;



public void Add (Author Author) {

Mapper.insertauthor (author);



Public Author GetByID (int id) {

return Mapper.selectauthorbyid (ID);



Public Author Getbyname (String username) {

Return Mapper.selectauthorbyname (username);



public void Update (Author Author) {

Mapper.updateauthor (author);



public void Delete (Author Author) {

Mapper.deleteauthor (author);




Encapsulation exception

Spring can encapsulate the exception of different technologies, such as Hibernate, JPA, into Spring's own level of exception. This allows us to handle exceptions uniformly in spring programs.

First of all, our DAO class needs @repository annotations.


public class Authordaoimpl implements Authordao {

private sqlsessiontemplate template;

Private Multimapper Mapper;


Public Authordaoimpl (sqlsessiontemplate template, Multimapper mapper) {

This.template = template;

This.mapper = mapper;


The other code omits


Then we need to declare the following two spring beans.

<!--exception Interceptor, used to encapsulate MyBatis as a spring exception-->

<bean class= "Org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean class= "Org.mybatis.spring.MyBatisExceptionTranslator" >

<constructor-arg type= "Javax.sql.DataSource" ref= "DataSource"/>

<constructor-arg type= "Boolean" value= "false"/>


This way the JDBC exception thrown in the code is translated into a spring exception. Since spring can encapsulate common JDBC exceptions for classes in @repository annotations, even without the above declaration, the exception we get is Spring's dataaccessexception. At first I thought Spring did not perform an abnormal conversion, and then I found out that spring was a very intimate print of the original anomaly and I got dizzy. If you catch an exception and then look at the exception type, you will find that it is already a spring exception.

Java Learning Data Acquisition (copy the next link to the browser)
data:text/html;charset=utf-8;base64,5p625p6e5bii5a2m5lmg6lwe5paz5ywn6ls56akg5y+w6k+35yqg5omj5omj5y+ 35pivmtaxodkyntc4ma==

discussion on various locks in Java and the optimal zookeeper distributed lock solution (VIDEO) Click on the Open link

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.