eclipse uses maven to build maven + database transactions

This article is reproduced to: http://www.cnblogs.com/java-zhao/p/5350106.html

In actual development, transactions are seldom used. Generally, transactions are mostly used in the aspect of money calculation.

After mybatis is integrated with spring, what should its transactions do? In fact, it is very simple to add the @Transactional annotation to the corresponding method (usually the service layer) directly on the basis of the code in the previous section.

1,com.wlsq.app.exception.UserException

package com.wlsq.app.exception;

import org.springframework.dao.DataAccessException;

public class UserException extends DataAccessException {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public UserException(String msg) {
		super(msg);
		// TODO Auto-generated constructor stub
	}

}
Note: This is a custom annotation that inherits the DataAccessException class.


2,com.wlsq.app.dao.UserDao

package com.wlsq.app.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.wlsq.app.domain.User;
import com.wlsq.app.exception.UserException;
import com.wlsq.app.mapper.UserMapper;

@Repository
public class UserDao {
	 	@Autowired
	    private UserMapper userMapper;
	    
	    public int insertUser(String loginname, String password){
	        return userMapper.insertUser(loginname, password);
	    }
	    
	    public int insertUserWithBackId(User user){    
	        return userMapper.insertUserWithBackId(user);
	    }
	    
	    public void testTransactional(String username){
	        throw new UserException("Test transaction");
	    }

}
Note: There are only two methods used for transaction testing in this class. The second method, testTransactional, throws a custom exception.


3,com.wlsq.app.service.UserService

package com.wlsq.app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wlsq.app.dao.UserDao;
import com.wlsq.app.domain.User;


@Service
public class UserService {
	@Autowired
	private UserDao userDao;

	 public boolean addUser(String loginname, String password){
	        return userDao.insertUser(loginname, password)==1?true:false;
	    }
	 
	   public User addUserWithBackId(String loginname, String password){
	        User user = new User();
	        user.setLoginname(loginname);
	        user.setPassword(password);
	        userDao.insertUserWithBackId(user);//After this method, the primary key has been set to user
	        return user;
	    }
	   
	   @Transactional
	    public void testTransaction(String username, String password){
	         System.out.println(userDao.insertUser(username, password));
	          userDao.testTransactional(username);
	    }

}

Description: Two methods of userDao mentioned above are called in this method.

The first method inserts a data into the database, and the second method throws our custom exception. If the transaction configuration is successful, the first method inserts the database and rolls back. Otherwise, the insertion of data is successful.


4,com.wlsq.app.web.UserController

package com.wlsq.app.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wlsq.app.domain.User;
import com.wlsq.app.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/user")
@Api("userController Relevant api")
public class UserController {
	@Autowired
    private UserService userService;

//    @RequestMapping("/getUser")
//    public User getUser() {
//        return userService.getUser();
//    }
    
    @ApiOperation("Registered User Information")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query",name="loginname",dataType="String",required=true,value="User's Name",defaultValue="zhaojigang"),
        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="User's password",defaultValue="wangna")
    })
    @ApiResponses({
        @ApiResponse(code=400,message="Request parameters not filled in"),
        @ApiResponse(code=404,message="No request path or incorrect page Jump path")
    })
    @RequestMapping(value="/getUser",method=RequestMethod.GET)
    public boolean getUser( @RequestParam("loginname") String username, @RequestParam("password") String password) {
        return userService.addUser(username,password);
    }
    
    @ApiOperation("Add a user and return to the one where the primary key has been set user Example")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query",name="loginname",dataType="String",required=true,value="User's Name",defaultValue="zhaojigang"),
        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="User's password",defaultValue="wangna")
    })
    @ApiResponses({
        @ApiResponse(code=400,message="Request parameters not filled in"),
        @ApiResponse(code=404,message="No request path or incorrect page Jump path")
    })
    @RequestMapping(value="/addUserWithBackId",method=RequestMethod.POST)
    public User addUserWithBackId(@RequestParam("loginname") String loginname, 
                                     @RequestParam("password") String password) {
        return userService.addUserWithBackId(loginname, password);
    }
    
    @ApiOperation("Test transaction")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query",name="loginname",dataType="String",required=true,value="User's Name",defaultValue="zhaojigang"),
        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="User's password",defaultValue="wangna")
    })
    @ApiResponses({
        @ApiResponse(code=400,message="Request parameters not filled in"),
        @ApiResponse(code=404,message="No request path or incorrect page Jump path")
    })
    @RequestMapping(value="/testTransaction",method=RequestMethod.GET)
    public void testTransaction(@RequestParam("loginname") String loginname, 
                                   @RequestParam("password") String password) {
       userService.testTransaction(loginname, password);
    }

}

Test: Start the service with the maven command - > swagger runs the URL - > to see if the database was inserted successfully


Question: After looking up a lot of information, mybatis is integrated with spring boot (data source uses druid). In order to add transactions, many people will do two things in the MyBatis Config class in the previous section.

  • Add the @EnableTransaction Management annotation to the MyBatis Config class, which enables annotated transaction management < tx: annotation-driven /> so that the @Transactional annotation of the method works, but without this sentence in the actual test, the @Transactional annotation is still useful
  • Adding a method to get transaction manager in MyBatis Config class
/**
     * Configuring Transaction Manager
     */
    @Bean
    @Primary
    public DataSourceTransactionManager transactionManager() throws Exception{
        return new DataSourceTransactionManager(getDataSource());
    }




 

Tags: Mybatis Database Spring Java

Posted on Fri, 19 Apr 2019 13:33:33 -0400 by Wien