Spring and mybatis integration and transaction control, springmybatis Integration

Source: Internet
Author: User

Spring and mybatis integration and transaction control, springmybatis Integration

I. Introduction

This article will use spring to integrate mybatis and add Transaction Management for future reference.


Ii. Example

1. code structure:



2. Table creation statement:

DROP DATABASE test;CREATE DATABASE test;    USE test;    CREATE TABLE USER(    id VARCHAR(36) PRIMARY KEY,    username VARCHAR(64),    address VARCHAR(128)   )    INSERT INTO USER (id, username, address) VALUES("001", "zhangsan", "Wuhan");  INSERT INTO USER (id, username, address) VALUES("002", "lisi", "Shanghai");   


3. entity class:

public class User {private String id;private String uname;private String address;@Overridepublic String toString() {return "id: " + id + ", uname: " + uname + ", address: " + address;}}
// The getter and setter methods are omitted.


4. Object ing 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>

Dynamically update user


5. service interface:

public interface UserService {void updateUser(User user);}

6. service implementation:

Public class UserServiceImpl implements UserService {private UserDao userDao; public void setUserDao (UserDao userDao) {this. userDao = userDao;} @ Overridepublic void updateUser (User user User) {userDao. updateUser (user); System. out. println (1/0); // runtime exception }}

7. dao interface:

public interface UserDao {User findUserById(String id);void updateUser(User user);}

8. dao implementation:

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {@Overridepublic User findUserById(String id) {SqlSession 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 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <typeAliases> <typeAlias type =" com. zdp. domain. user "alias =" User "/> </typeAliases> <mappers> <! -- Ing file location --> <mapper resource = "com/zdp/domain/User. xml"/> </mappers> </configuration>

10. 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 the 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"/> <! -- Location of the mybatis configuration file --> <property name = "configLocation" value = "classpath: sqlMapConfig. xml"/> </bean> <! -- Configure 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 *" propagatio N = "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 "*" indicates all classes, and the second "*" indicates all methods ,".. "represents any parameter --> <aop: pointcut id =" pointcut "expression =" execution (* com. zdp. service. *. *(..)) "/> <! -- Control transactions at the service layer --> <aop: advisor pointcut-ref = "pointcut" advice-ref = "transactionAdvice"/> </aop: config> <! -- 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>

11. junit testing:

public class SpringTest {private ApplicationContext context;@Beforepublic void sprintInit() {context = new ClassPathXmlApplicationContext("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);}}







Springmvc + mybatis integrated Transaction Management

<! -- Transaction-related control -->
<Bean id = "transactionManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager">
<Property name = "dataSource" ref = "dataSource"> </property>
</Bean>
<Tx: advice id = "txAdvice" transaction-manager = "transactionManager">
<Tx: attributes>
<Tx: method name = "add *" propagation = "REQUIRED" read-only = "false" rollback-for = "java. lang. Exception"/>
<Tx: method name = "delete *" propagation = "REQUIRED" read-only = "false" rollback-for = "java. lang. Exception"/>
<Tx: method name = "modify *" propagation = "REQUIRED" read-only = "false" rollback-for = "java. lang. Exception"/>
<Tx: method name = "update *" propagation = "REQUIRED" read-only = "false" rollback-for = "java. lang. Exception"/>
<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>
<! -- Control transactions at the Service layer -->
<Aop: config>
<Aop: pointcut id = "pc" expression = "execution (public * com. test. serv ...... the remaining full text>

How does spring integrate with mybatis to close transactions at the service layer? Configure with xml

First, the transaction is not closed based on whether the service layer is used up, but when the session you open is used up and at which layer it is used up. In general, the method names are prefixed in the transaction configuration file.
For example:
<Tx: method name = "save *" propagation = "REQUIRED"/>
This method is managed by transactions when the service layer calls the saveXXX method. In this save method, the session is enabled when the dao layer queries the data you want. When you have finished executing this save method, the transaction is automatically closed, and the session is also automatically closed, all of which are managed by spring.

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.