Detailed Java MyBatis Framework and Spring Framework integration application _java

Source: Internet
Author: User
Tags aop rollback

There are many limitations to using mybatis alone (such as the inability to implement transactions spanning multiple sessions), and many business systems are inherently transactions that are managed using spring, so mybatis is best integrated with spring.

Version requirements

Project

Version

Download Address

Description

MyBatis

3.0 and above

Https://github.com/mybatis/mybatis-3/releases

Spring

3.0 and above

http://projects.spring.io/spring-framework/

Mybatis-spring

1.0 and above

Https://github.com/mybatis/spring/releases


Spring Transaction Configuration

<!--automatic scanning business package--> 
<context:component-scan base-package= "Com.xxx.service"/> 
 
<!--data source--> 
<jee:jndi-lookup id= "Jndidatasource" jndi-name= "Java:comp/env/jdbc/datasource"/> 
 
<!--configuration Transaction-- > 
<bean id= "Txmanager" 
    class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > 
  <property name= "DataSource" ref= "Jndidatasource"/> 
</bean> 
<!--configuring annotation based things AOP > 
<tx:annotation-driven transaction-manager= "Txmanager" proxy-target-class= "true"/> 

Single integration

<!--integrated MyBatis--> <bean id= "sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" 
> 
  <property name= "DataSource" ref= "Jndidatasource"/> <property name= "Configlocation" 
  Classpath:/mybatis/mybatis-config.xml "/> 
  <!--automatic configuration alias--> 
  <property name=" Typealiasespackage " Value= "Com.xxx.dto"/> 
</bean> 
 
<!--create DAO beans (only provide interfaces without providing implementation classes)--> 
<bean id= "Userdao" class= "Org.mybatis.spring.mapper.MapperFactoryBean" > 
  <property name= "Mapperinterface" Com.xxx.dao.UserDao "/> 
  <property name= sqlsessionfactory" ref= "Sqlsessionfactory"/> 
> 

We should not only understand how to use it, but also why we should use it.

Sqlsessionfactorybean is a factory bean, and its role is to parse the configuration (data source, alias, etc.).

Mapperfactorybean is a factory bean, and in the spring container, the factory bean has a special purpose, and when spring injects the factory bean into the other bean, Instead of injecting the factory bean itself, it invokes the GetObject method of the Bean. Let's look at what this getobjec has done:

Public T GetObject () throws Exception {return 
 getsqlsession (). Getmapper (This.mapperinterface); 
} 

See here everyone should be very clear, this method and we used to use the MyBatis the same way, are first to obtain a Sqlsession object, and then from the sqlsession to get Mapper objects (again stressed that Mapper is a proxy object, It proxies the Mapperinterface interface, which is the user-supplied DAO interface. Naturally, the final injection into the business layer is the Mapper object.

The actual project is usually more than one DAO, and if you have multiple DAO then configure it according to the configuration above.

How to use Bulk updates
the previous section discusses how to inject a mapper object into the business layer, mapper behavior relies on configuration, MyBatis uses a single update by default (that is, executortype defaults to simple instead of batch), Of course, we can modify the default behavior by modifying the MyBatis configuration file, but if we just want one or a few mapper to use the batch update, it's not OK. This is when we need to use template technology:

<!--custom MyBatis behavior through templates--> 
lt;bean id= "Sqlsessiontemplatesimple" class= " Org.mybatis.spring.SqlSessionTemplate ">   
<constructor-arg index=" 0 "ref=" sqlsessionfactory "/> 
<!--update takes single mode--> 
<constructor-arg index= "1" value= "simple"/> 
</bean> 
   
<!-- Customizing MyBatis behavior through Templates--> 
lt;bean id= "Sqlsessiontemplatebatch" class= "Org.mybatis.spring.SqlSessionTemplate" >   
<constructor-arg index= "0" ref= "sqlsessionfactory"/> 
<!--update using batch mode--> 
< Constructor-arg index= "1" value= "BATCH"/> 
</bean> 

Here the author defines two template objects, one using a single update and one using a batch update. With the template we can change the way mapper behaves:

<bean id= "Userdao" class= "Org.mybatis.spring.mapper.MapperFactoryBean" > 
  <property name= " Mapperinterface "value=" Com.xxx.dao.UserDao "/> <property name=" sqlsessiontemplate "ref=" 
  Sqlsessiontemplatebatch "/> 


Unlike the mapper configuration in the previous section, there is no need to configure the Sqlsessionfactory property, only to configure Sqlsessiontemplate (the Sqlsessionfactory attribute is already configured in the template).

Simplifies mapper configuration with automatic scanning
as you can see in the previous section, our DAO needs one configuration in the configuration file, and if there are many DAO, the configuration file will be very large, so it will be more painful to manage. Thankfully, the MyBatis team was aware of this, using spring's automated scanning capabilities to encapsulate a tool class that automatically scans DAO, so that we can use this feature to simplify configuration:

<!--Create mapper beans (single update mode)--> <bean class= by automatic scanning 
org.mybatis.spring.mapper.MapperScannerConfigurer "> 
  <property name=" basepackage "value=" Com.xxx.dao "/> <property name= 
  " Sqlsessiontemplatebeanname "value=" Sqlsessiontemplatesimple "/> <property name=" markerInterface "value=" 
  Com.xxx.dao.SimpleDao "/> 
</bean> 
    
<!--create mapper beans (batch update mode)--> <bean class= by automatic scanning 
"Org.mybatis.spring.mapper.MapperScannerConfigurer" > 
  <property name= "basepackage" value= "Com.xxx.dao"/ > 
  <property name= "Sqlsessiontemplatebeanname" value= "Sqlsessiontemplatebatch"/> 
  <property Name= "Markerinterface" value= "Com.xxx.dao.BatchDao"/> 
</bean> 

Mapperscannerconfigurer itself involved in the spring technology I will not say more, interested in and the spring principle of more understanding can go to see its source code. Let's take a look at its three properties:

    • Basepackage: The base package name that the scanner begins to scan, and supports nested scans;
    • Sqlsessiontemplatebeanname: The name of the template bean mentioned above;
    • Markerinterface: interface based filter, which implements the interface of DAO will be scanned by the scanner, and Basepackage is the role.

In addition to using interface filtering, you can also use annotation filtering:

<!--Create mapper beans (batch update mode)--> <bean class= by automatic scanning 
org.mybatis.spring.mapper.MapperScannerConfigurer "> 
  <property name=" basepackage "value=" Com.xxx.dao "/> <property name= 
  " Sqlsessiontemplatebeanname "value=" Sqlsessiontemplatebatch "/> <property name=" AnnotationClass "value=" 
  Com.xxx.dao.BatchAnnotation "/> 
</bean> 

Annotationclass: The DAO configured with this annotation will be scanned by the scanner, and the basepackage is the role.

It should be noted that two filter conditions can only be matched with one.

Instance: Transaction Management
define an entity class: Emp.java

Package com.lixing.scm.entity;

public class Emp {
 private String ID;
 private String name;
 Private String sex;
 private int age;
 Private String phone;
 Public String GetId () {return
  ID;
 }
 public void SetId (String id) {
  this.id = ID;
 }
 Public String GetName () {return
  name;
 }
 public void SetName (String name) {
  this.name = name;
 }
 Public String Getsex () {return
  sex;
 }
 public void Setsex (String sex) {
  this.sex = sex;
 }
 public int getage () {return age
  ;
 }
 public void Setage (int age) {
  this.age = age;
 }
 Public String Getphone () {return
  phone;
 }
 public void Setphone (String phone) {
  this.phone = phone;
 }
}

Define internal operation interfaces for entities: Empmapper.java

Package com.lixing.scm.test.mapper;

Import java.util.List;
Import Java.util.Map;

Import COM.LIXING.SCM.ENTITY.EMP;

Public interface Empmapper {
 void insertemp (emp emp);
 List<emp> getallemp ();
 EMP GetByID (String ID);
 void Deleteemp (String id);
 void Updateemp (map<string,object> Map);


Defines the mapping file for an entity class action interface: Empmapper.xml

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > & Lt;mapper namespace= "Com.lixing.scm.test.mapper.EmpMapper" > <parametermap type= "com.lixing.scm.entity.Emp" Id= "Parametermapemp" > <parameter property= "id"/> <parameter property= "name"/> <parameter property= "Sex"/> <parameter property= "age"/> <parameter property= "Phone"/> </parameterMap> <resultm AP type= "Com.lixing.scm.entity.Emp" id= "resultmapemp" > <result property= "id" column= "id"/> <result
  ty= ' name ' column= ' name '/> <result property= ' sex ' column= ' sex '/> <result property= ' age ' column= ' age '/> <result property= "Phone" column= "phone"/> </resultMap> <insert id= "insertemp" parametermap= "parameter"
 Mapemp "> INSERT into EMP (id,name,sex,age,phone) VALUES (?,?,?,?,?) </insert> <selectId= "Getallemp" resultmap= "resultmapemp" > SELECT * from emp </select> <select id= "GetByID" String "resultmap=" resultmapemp > select * from emp WHERE id=#{value} </select> <delete id= "Deleteemp" p Arametertype= "String" > DELETE from emp WHERE id=#{value} </delete> <update id= "Updateemp" ParameterType = "Java.util.Map" > UPDATE emp SET name=#{name},sex=#{sex},age=#{age},phone=#{phone} WHERE Id=#{id} </update&gt
; </mapper> Spring3.0.6 definition: applicationcontext.xml <?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" Http://www.springframework.org/schema/beans "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "Xmlns:context = "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-bEans-3.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring- Context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0. 

 xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!----> <context:annotation-config/> <context:component-scan base-package= "com.lixing.scm.test.*"/ > <!--jdbc.propertis Directory--> <bean class= "Org.springframework.beans.factory.config.PropertyPlaceh Olderconfigurer "> <property name=" Locations "value=" classpath:jdbc.properties "/> </bean> <bean id= "myDataSource" destroy-method= "Close" class= "Org.apache.commons.dbcp.BasicDataSource" > <property name= "  Driverclassname "value=" ${jdbc.driverclassname} "/> <property name=" url "value=" ${jdbc.url} "/> Name= "username" value= "${jdbc.useRname} "/> <property name= password" value= "${jdbc.password}"/> </bean> <!--sqlsessionfactory--&
 Gt <bean id= "Sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "DataSource" "ref=" myDataSource "/> </bean> <!--scanmapperfiles--> <bean class=" Org.mybatis.spring.mapper.Mapp Erscannerconfigurer "> <property name=" basepackage "value=" Com.lixing.scm.test.mapper "/> </bean> ;! --================================ transaction related control =================================================--> <bean name= " TransactionManager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property nam E= "DataSource" ref= "myDataSource" ></property> </bean> <tx:advice id= "Usertxadvice" transaction-m Anager= "TransactionManager" > <tx:attributes> <tx:method name= "delete*" propagation= "REQUIRED" read-only = "false" Rollback-fOr= "Java.lang.Exception" no-rollback-for= "java.lang.RuntimeException"/> <tx:method name= "insert*" propagation= "REQUIRED" read-only= "false" rollback-for= "Java.lang.RuntimeException"/> <tx:method N Ame= "update*" propagation= "REQUIRED" read-only= "false" rollback-for= "Java.lang.Exception"/> < Tx:method name= "find*" propagation= "SUPPORTS"/> <tx:method name= "get*" propagation= "SUPPORTS"/> <tx:meth OD name= "select*" propagation= "SUPPORTS"/> </tx:attributes> </tx:advice> <aop:config> <a Op:pointcut id= "PC" expression= "Execution (public * com.lixing.scm.test.service.*.* (..))"/> <!--  Control the transaction in the service layer--> <aop:advisor pointcut-ref= "PC" advice-ref= "Usertxadvice"/> </aop:config> <!-- The following is the custom bean--> <bean id= "Empdao" class= "Com.lixing.scm.test.dao.impl.EmpDaoImpl" autowire= "ByName"/> <be An id= "Empservice" class= "Com.lixing.scm.test.service.impl".Empserviceimpl "autowire=" ByName "/> </beans>

 

DAO Interface: Empdao.java

Package Com.lixing.scm.test.dao;

Import java.util.List;
Import Java.util.Map;

Import COM.LIXING.SCM.ENTITY.EMP;

Public interface Empdao {
 void insertemp (emp emp);
 List<emp> getallemp ();
 EMP GetByID (String ID);
 void Deleteemp (String id);
 void Updateemp (map<string, object> Map);


DAO interface Implementation class: Empdaoimpl.java

Package Com.lixing.scm.test.dao.impl;
Import java.util.List;

Import Java.util.Map;
Import COM.LIXING.SCM.ENTITY.EMP;
Import Com.lixing.scm.test.dao.EmpDao;

Import Com.lixing.scm.test.mapper.EmpMapper;  public class Empdaoimpl implements Empdao {private Empmapper empmapper; Inject a empmapper///This empmapper automatically generated by spring//No need to manually define @Override public void Insertemp (EMP emp) {THIS.EMPMA
  Pper.insertemp (EMP);  throw new RuntimeException ("Error"); Test throws RuntimeException//exception to see if the database exists record} @Override public void deleteemp (String id) {THIS.EMPMAPPER.DELETEEMP (id
 );
 @Override public list<emp> getallemp () {return this.empMapper.getAllEmp ();
 @Override public Emp GetByID (String ID) {return this.empMapper.getById (ID);
 @Override public void Updateemp (map<string, object> map) {THIS.EMPMAPPER.UPDATEEMP (map);
 Public Empmapper Getempmapper () {return empmapper; } public void Setempmapper (Empmapper empmapper) {this.empmapper =Empmapper;

 }
}

Service Layer Interface: Empservice.java

Package com.lixing.scm.test.service;

Import COM.LIXING.SCM.ENTITY.EMP;

Public interface Empservice {
 void insertemp (emp emp);
}

Service Layer Interface Implementation class: Empserviceimpl.java

Package Com.lixing.scm.test.service.impl;

Import COM.LIXING.SCM.ENTITY.EMP;
Import Com.lixing.scm.test.dao.EmpDao;
Import Com.lixing.scm.test.service.EmpService;

public class Empserviceimpl implements Empservice {
 private Empdao Empdao;

 @Override public
 void Insertemp (emp emp) {
  empdao.insertemp (EMP);

 }

 Public Empdao Getempdao () {return
  Empdao;
 }

 public void Setempdao (Empdao empdao) {
  This.empdao = Empdao;
 }
}

Test class: Testempservice.java

Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import COM.LIXING.SCM.ENTITY.EMP;
Import Com.lixing.scm.test.service.EmpService;


public class Testempservice {
 @Test the public
 void Testtrasaction () {
  emp emp=new emp ();
  Emp.setid ("00000003");
  Emp.setname ("So-and-so");
  Emp.setage (m);
  Emp.setsex ("male");
  Emp.setphone ("566666");
  
  ApplicationContext ctx=new classpathxmlapplicationcontext ("Classpath:applicationContext.xml");
  Empservice Service=ctx.getbean (empservice.class);
  Service.insertemp (EMP);
 }

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.