step1:配置xml文件
step2:自动注入TransactionTemplate对象
1 import org.springframework.transaction.support.TransactionTemplate; 2 @Autowired3 private TransactionTemplate transactionTemplate;
step3:使用execute方法对事务进行管理
1 transactionTemplate.execute(new TransactionCallbackWithoutResult() {2 3 @Override4 protected void doInTransactionWithoutResult(TransactionStatus arg0) {5 String s = userService.newUser(user,currentUserId);6 User newUser=userService.getUser(user.getUsername());7 roleService.createRoleUser(newUser.getUserId(), rolesId);8 }9 });
完整流程如下:
1 package com.superb.mips.terminal.rest.controller; 2 3 import java.util.HashMap; 4 5 import org.apache.commons.lang3.StringUtils; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.transaction.TransactionStatus; 9 import org.springframework.transaction.annotation.Transactional;10 import org.springframework.transaction.support.TransactionCallbackWithoutResult;11 import org.springframework.transaction.support.TransactionTemplate;12 import org.springframework.web.bind.annotation.RequestMapping;13 import org.springframework.web.bind.annotation.ResponseBody;14 15 import com.superb.mips.system.domain.User;16 import com.superb.mips.system.service.inf.RoleService;17 import com.superb.mips.system.service.inf.UserService;18 19 20 @Controller21 @RequestMapping("api/users")22 public class RestUserController {23 @Autowired24 private UserService userService;25 &orgName=中国移动&orgId=126 @Autowired27 private RoleService roleService;28 @Autowired29 private TransactionTemplate transactionTemplate;30 31 @RequestMapping(value = "/createUsers.json")32 @ResponseBody33 @Transactional34 public HashMapcreateUser(final User user,final int currentUserId,final String rolesId) {35 HashMap map = new HashMap ();36 String[] strAry=rolesId.split(",");37 if(strAry.length==0){38 map.put("result", 1);39 map.put("description", "请绑定角色");40 return map;41 }else{42 for(int i=0;i