Spring and MyBatis integration and transaction control

Source: Internet
Author: User

One. Basic introduction

This article will use spring to integrate the MyBatis and add transaction management as a note for easy reference.


Two. Examples

1. Code structure diagram:



2. Build the Table statement:

DROP DATABASE test; CREATE DATABASE test;    Use test;    CREATE TABLE USER (    ID varchar (PRIMARY) KEY,    username varchar (+),    address varchar (+)   )    INSERT into USER (ID, username, address) VALUES ("001", "Zhangsan", "Wuhan");  INSERT into USER (ID, username, address) VALUES ("002", "Lisi", "Shanghai");   


3. Entity classes:

public class User {private string Id;private string uname;private string address; @Overridepublic string toString () {return "ID:" + ID + ", uname:" + uname + ", Address:" + Address;}}
//Omit getter and Setter methods


4. Entity Mapping configuration: User.xml

<?xml Version= "1.0" encoding= "UTF-8"? 

><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Com.zdp.domain.User" ><resultmap type= "User" id= "UserBean" ><id column= "id" property= " ID "/><result column=" username "property=" uname "/><result column=" Address "property=" Address "/></ Resultmap><select id= "Selectuserbyid" parametertype= "string" resultmap= "UserBean" >select * from user where ID = #{id}</select><update id= "updateuserbycondition" parametertype= "User" >update user<set><if Test= "Uname! = null" >username = #{uname}, </if><if test= "Address! = NULL" >address = #{address}</if> </set>where id = #{id}</update></mapper>

Update user dynamically


5. Service Interface:

public interface UserService {void UpdateUser (user user);

6. Service implementations:

public class Userserviceimpl implements UserService {private Userdao userdao;public void Setuserdao (Userdao userdao) {thi S.userdao = Userdao;} @Overridepublic void UpdateUser (user user) {userdao.updateuser (user); System.out.println (1/0); Execution-time Exception}}

7. DAO Interface:

Public interface Userdao {User Finduserbyid (String id); void updateUser (user user);}

8. DAO Implementations:

public class Userdaoimpl extends Sqlsessiondaosupport implements Userdao {@Overridepublic User Finduserbyid (String id) {S Qlsession sqlsession = Super.getsqlsession (); User user = (user) Sqlsession.selectone (User.class.getName () + ". Selectuserbyid", id); return user;} @Overridepublic void UpdateUser (user user) {super.getsqlsession (). Update (User.class.getName () + ". Updateuserbycondition ", user);}}

9. MyBatis Global configuration: Sqlmapconfig.xml

<?

XML version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><typealiases><typealias type= "Com.zdp.domain.User" alias= "User"/></ typealiases><mappers>< the location of the!--mapping file --><mapper resource= "Com/zdp/domain/user.xml"/></ Mappers></configuration>


Spring Configuration: 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 "><!--Configure Data source--><bean id=" DataSource "class=" Org.springframework.jdbc.datasource.DriverManagerDataSource "><property name=" Driverclassname "value=" Com.mysql.jdbc.Driver "/><property name=" url"Value=" jdbc:mysql:///test "/><property name=" username "value=" root "/><property name=" password "value=" Root "/></bean><!--session factory--><bean id=" Sqlsessionfactory "class=" Org.mybatis.spring.SqlSessionFactoryBean "><property name=" DataSource "ref=" DataSource "/><!-- MyBatis the location of the total configuration file--><property name= "configlocation" value= "Classpath:sqlMapConfig.xml"/></bean>< !--Configuring transaction Management--><bean name= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "><property name=" datasource "ref=" DataSource "/></bean><tx:advice id=" Transactionadvice "transaction-manager=" TransactionManager "> <tx:attributes> <tx:method name= "delete*" propagation= "REQUIRED"/> <tx:method name= "Save * "propagation=" REQUIRED "/> <tx:method name=" update* "propagation=" REQUIRED "/> <tx:method Name= "find*" read-only= "true"/> <tx:methOD name= "get*" read-only= "true"/> <tx:method name= "select*" read-only= "true"/> </tx:attributes > </tx:advice> <aop:config> <!--the first "*" represents all classes, the second "*" represents all methods, "..." Delegate optional--<aop:pointcut id= "pointcut" expression= "Execution (* com.zdp.service.*.* (..))"/> <!-- Control the transaction at the service layer--<aop:advisor pointcut-ref= "pointcut" advice-ref= "Transactionadvice"/> </aop:config& Gt <!--business processing--><bean id= "Userdao" class= "Com.zdp.dao.impl.UserDaoImpl" ><property name= " Sqlsessionfactory "ref=" sqlsessionfactory "/></bean><bean id=" UserService "class=" Com.zdp.service.impl.UserServiceImpl "><property name=" Userdao "ref=" Userdao "/></bean></beans >


junit Test:

public class Springtest {private applicationcontext context; @Beforepublic void Sprintinit () {context = new Classpathxmlap Plicationcontext ("Applicationcontext.xml");} @Testpublic void Testfinduserbyid () {Userdao Userdao = (Userdao) context.getbean ("Userdao"); User user = Userdao.finduserbyid ("001"); SYSTEM.OUT.PRINTLN (user);} @Testpublic void Testupdateuser () {UserService userservice = (userservice) context.getbean ("UserService"); User user = new user (), User.setid ("001"), User.setuname ("Zhangsan1"); Userservice.updateuser (user);}}






Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Spring and MyBatis integration and transaction control

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.