SpringMVC,Mybatis结合事务Transaction
5.SpringMVC,Mybatis结合事务Transaction
前面讲过,Spring事务就是针对某一个方法,在头和尾环绕上一对儿事务的开始和结束语句段,方法里针对数据库的操作就成为了一个事务。具体怎么样访问数据库,是JDBC,还是Spring JDBC还是Mybatis,Spring的事务并不关心。所以mybatis这里的事务的配置和实验和前面的Spring JDBC是一样的。
例 1.5
package com;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@Resource
private ILoginService loginServic;
@RequestMapping("/helloa")
public void helloWorld(HttpServletResponse res) throws IOException {
loginServic.login();
res.sendRedirect("index.jsp");
}
}
package com;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.mapper.RegisterMapper;
@Service
public class LoginServiceImpl implements ILoginService {
@Resource
private RegisterMapper registerMapper;
public void login() {
updateRegister();
System.out.println("successfully update 1");
insertRegisterWrong();//duplicate key
System.out.println("successfully insert 2");
}
public void updateRegister() {
Register registerU = new Register();
registerU.setId(52);
registerU.setName("bbb2");
registerU.setAge(80);
System.out.println("registerMapper.updateByPrimaryKey 的返回值是 "+registerMapper.updateByPrimaryKey(registerU));
}
public void insertRegisterWrong() {
Register register = new Register();
register.setAge(80);
register.setId(50);
register.setName("aaa");
registerMapper.insert(register); }
}
更多内容请见原文,原文转载自:https://blog.csdn.net/qq_44639795/article/details/100173346