Spring+mybatis+mysql+maven simple case of transaction management

Source: Internet
Author: User

Use MAVEN to manage the jar packages in your project, while using spring to manage transactions at the business processing level. The database uses MYSQ, and the data processing layer is combined with spring and mybatis.

The main structure of this case code

1. Database Scripts


2.maven configuration file Pom.xml

<project xmlns= "http://maven.apache.org/POM/4.0.0"  xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance " xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/ Xsd/maven-4.0.0.xsd "> <modelversion>4.0.0</modelversion> <groupid>com.hskj</ groupid> <artifactid>maven_spring</artifactid> <version>0.0.1-snapshot</ version> <packaging>war</packaging> <dependencies>  <!--  Junit testing framework -->  <dependency>   <groupid> Junit</groupid>   <artifactid>junit</artifactid>   <version >3.8.1</version>   <scope>test</scope>  </dependency>   <!-- Spring framework -->  <dependency>   < Groupid>org.springframework</grouPid>   <artifactid>spring-context</artifactid>   <version> 3.2.6.release</version>  </dependency>  <dependency>    <groupid>org.springframework</groupid>   <artifactid>spring-jdbc</ Artifactid>   <version>3.2.6.release</version>  </dependency>   <!-- Spring AOP dependency -->  <dependency>    <groupId>cglib</groupId>   <artifactId>cglib</artifactId>    <version>2.2</version>  </dependency>  <!-- mysql  database driver -->  <dependency>   <groupId>mysql< /groupid>   <artifactid>mysql-connector-java</artifactid>   < Version>5.0.5</version>  </dependency>  <dependency>   <groupid>dom4j</ groupid>   <artifactid>dom4j</artifactid>   <version>1.6.1 </version>  </dependency>  <dependency>   <groupId> commons-logging</groupid>   <artifactid>commons-logging</artifactid>    <version>1.1.1</version>  </dependency>  <dependency>    <groupId>commons-collections</groupId>   <artifactId> commons-collections</artifactid>   <version>3.2.1</version>  </ dependency>  <dependency>   <groupid>antlr</groupid>    <artifactId>antlr</artifactId>   <version>2.7.7</version>   </dependency>  <dependency>   <groupid>org.mybatis</groupid>   < artifactid>mybatis</artifactid>   <version>3.2.3</version>  < /dependency>  <dependency>   <groupid>org.mybatis</groupid>    <artifactid>mybatis-spring</artifactid>   <version>1.2.1 </version>  </dependency>  <dependency>   <groupId> C3p0</groupid>   <artifactid>c3p0</artifactid>   <version >0.9.1.2</version>  </dependency>  <dependency>   < Groupid>org.aspectj</groupid>   <artifactid>aspectjweaver</artifactid>    <version>1.7.4</version>  </dependency> </dependencies ></project>

3. Database configuration file Config.properties

db.driverclass=org.gjt.mm.mysql.driverdb.jdbcurl=jdbc:mysql://localhost:3306/testdb.user=rootdb.password=root# Db.initialpoolsize=20db.maxidletime=60db.maxpoolsize=200db.minpoolsize=50#db.acquireincrement= 3db.acquireretrydelay=1000db.acquireretryattempts=30db.breakafteracquirefailure=false

4.Spring configuration file 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:tx= "Http://www.springframework.org/schema/tx" xmlns:aop= "Http://www.springframework.org/schema/aop" xmlns:       Mvc= "Http://www.springframework.org/schema/mvc" 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/sche     Ma/tx http://www.springframework.org/schema/tx/spring-tx.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframework.org/schema/mvc http ://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ";<!--Load configuration file--><context:property-placeholder location= "config.properties"/><!--Specify the spring annotation injection layer-- ><context:component-scan base-package= "com.hskj"/><!--database connection pool management--><bean id= "C3p0DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "Close" ><property name= "Driverclass" value = "${db.driverclass}" ></property><property name= "Jdbcurl" value= "${db.jdbcurl}" ></property> <property name= "user" value= "${db.user}" ></property><property name= "password" value= "${db.password} "></property><property name=" initialpoolsize "value=" ${db.initialpoolsize} "></property>< !--maximum idle time, unused in 60 seconds, the connection is discarded. If 0, it will never be discarded. default:0--><property name= "MaxIdleTime" value= "${db.maxidletime}" ></property><!--the maximum number of connections left in the connection pool. Default:15--><property name= "maxpoolsize" value= "${db.maxpoolsize}" ></property><property name= " Minpoolsize "value=" ${db.minpoolsize} "></property><!--c3p0 The number of connections that are fetched at the same time when the connection in the connection pool is exhausted. Default:3--><property name= "acquireincrement" value= "${db.acquireincrement}" ></property><!-- Interval in two connections, in milliseconds. default:1000--><property name= "Acquireretrydelay" value= "${db.acquireretrydelay}" ></property>< !--defines the number of repeated attempts to obtain a new connection from the database after a failure. default:30--><property name= "acquireretryattempts" value= "${db.acquireretryattempts}" ></property> <!--getting a connection failure will cause any thread that waits for the connection pool to get the connection to throw an exception. However, the data source is still valid and continues to try to get the connection the next time you call Getconnection (). If set to True, the data source will declare broken and permanently shut down after attempting to acquire a connection failure. Default:false--><property name= "breakafteracquirefailure" value= "${db.breakafteracquirefailure}" ></ property></bean><!--================================ Transaction-related control ======================================== =========--><bean name= "TransactionManager" class= " Org.springframework.jdbc.datasource.DataSourceTransactionManager "><property name=" datasource "ref=" C3p0datasource "></property></bean><tx:advice id=" Usertxadvice "trAnsaction-manager= "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 name= "update*" propagation= "REQUIRED" read-only= "false" rollback-for= "Java.lang.Exception"/> <tx:method name= "find*" propagation= "SUPPORTS"/><tx:method name= "get*" propagation= "SUPPORTS"/&GT;&LT;TX: Method Name= "select*" propagation= "SUPPORTS"/></tx:attributes></tx:advice><aop:config>< Aop:pointcut id= "PC" expression= "Execution (public * com.hskj.service.*.* (..))"/> <!--to control transactions at the service layer-->< Aop:advisor pointcut-ref= "PC" advice-ref= "Usertxadvice"/></aop:config><bean id= "SqlSessionFactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" ><property name= "DataSource" ref= "C3p0datasource"/><property name=" configlocation "value=" Mybatis-configuration.xml "/></bean><bean class=" Org.mybatis.spring.mapper.MapperFactoryBean "><property name=" Mapperinterface "value=" Com.hskj.mapper.UserMapper "/><property name=" sqlsessionfactory "ref=" Sqlsessionfactory "/></bean> </beans>

5.MyBatis configuration file Mybatis-configuration.xml, Userdaomapper.xml

(1) Mybatis-configuration.xml<?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> <mappers> <mapper resource= "Userdaomapper.xml"/> </mappers></confi Guration> (2) userdaomapper.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" > < Mapper namespace= "Com.hskj.mapper.UserMapper" > <parametermap type= "com.hskj.domain.User" id= "    Parametermapuser "> <parameter property=" id "/> <parameter property=" name "/> </parameterMap> <resultmap type= "Com.hskj.domain.User" id= "Resultmapuser" > <result property= "id" column= "id"/> <resul T property= "name" column= "name"/> </resultMap> <insert id= "Insertuser" parametermap= "Parametermapuser" &    Gt INSERT into user (ID, name) VALUES (?,?)  </insert> <select id= "Countall" resulttype= "int" > SELECT count (*) c from user; </select> <select id= "Getalluser" resultmap= "Resultmapuser" > select * from User </select> <sel ECT id= "getById" parametertype= "String" resultmap= "Resultmapuser" > select * from user WHERE Id=#{value} </sel  ect> <delete id= "DeleteUser" parametertype= "String" > Delete from user WHERE Id=#{value} </delete> <update id= "UpdateUser" parametertype= "Java.util.Map" > Update user SET Name=#{name} WHERE Id=#{id} </u Pdate></mapper>

Here is the Java Source section, Spring uses annotation injection

6.UserMapper class

Package Com.hskj.mapper;import Java.util.list;import Java.util.map;import org.springframework.stereotype.Service; Import Com.hskj.domain.User; @Service ("Usermapper") public interface Usermapper {public    int countall ();    public void Insertuser (user user);    Public list<user> Getalluser ();    Public User getById (String ID);    public void DeleteUser (String id);    public void UpdateUser (map<string,object> Map);}

7.UserDao class

Package Com.hskj.dao;import java.util.list;import Java.util.map;import Com.hskj.domain.user;public interface UserDao {Public    int countall ();    public void Insertuser (user user);    Public list<user> Getalluser ();    Public User getById (String ID);    public void DeleteUser (String id);    public void UpdateUser (map<string,object> Map);}

8.UserDaoImpl class

Package Com.hskj.daoimpl;import Java.util.list;import Java.util.map;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Com.hskj.dao.userdao;import Com.hskj.domain.user;import Com.hskj.mapper.UserMapper, @Service ("Userdao") public Class Userdaoimpl implements userdao{@Autowiredprivate usermapper usermapper;public int Countall () {return  This.userMapper.countAll ();} @Overridepublic void Insertuser (user user) {this.userMapper.insertUser (user);} @Overridepublic list<user> Getalluser () {return This.userMapper.getAllUser ();} @Overridepublic User getById (String ID) {return this.userMapper.getById (ID);} @Overridepublic void DeleteUser (String id) {this.userMapper.deleteUser (id);} @Overridepublic void UpdateUser (map<string, object> map) {this.userMapper.updateUser (map);}}

9.UserService class

Package Com.hskj.service;import Java.util.map;import Com.hskj.domain.user;public interface UserService {public    int Countall ();    public void Insertuser (user user);    public void Update_insert (Map map,user User);

10.UserServiceImpl class

Package Com.hskj.serviceimpl;import Java.util.map;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.service;import Com.hskj.dao.userdao;import Com.hskj.domain.user;import Com.hskj.service.UserService, @Service ("UserService") public class Userserviceimpl implements UserService {    @ Autowiredprivate Userdao Userdao;  public int Countall () {        return this.userDao.countAll ();    } @Overridepublic void Insertuser (user user) {this.userDao.insertUser (user); throw new RuntimeException ("Error");} @Overridepublic void Update_insert (map Map,user User) {this.userDao.updateUser (map); This.userDao.insertUser (user); throw new RuntimeException ("Error");}    }

11.User class

Package Com.hskj.domain;public class User {private string Id;private string Name;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 user () {}public User (string ID, string name) {super (); this.id = Id;this.name = name;}}

12.UserServiceTest class

Import Java.util.hashmap;import Java.util.map;import Org.junit.test;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.hskj.domain.user;import Com.hskj.service.userservice;public class Userservicetest {@Test public void Userservicetest () {@Suppres        Swarnings ("resource") applicationcontext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");        UserService UserService = (userservice) context.getbean ("UserService");        User User =new User ();        User.setid ("003");                User.setname ("Cherry wood Flower Road");        Map map=new HashMap ();        Map.put ("id", "001");        Map.put ("Name", "Ark Son");        try {System.out.println (Userservice.countall ());        Userservice.update_insert (map, user);                 Userservice.insertuser (user);//} catch (Exception e) {e.printstacktrace ();} }}

Source code: Http://pan.baidu.com/s/1ntHgGul

Spring+mybatis+mysql+maven simple case of transaction management

Related Article

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.