先来假设这样一个问题:如果数据库里面有一个用户表和一个作家表,那么当要添加一条数据到作家表中时,作家表的id必须是用户表中的其中一个id,因为作家一定也要是一个用户。这时就涉及到事务处理。
在上一篇博客的基础上,同时添加一个人的信息到用户表和作家表,如果失败则需要事务回滚
在pojo包中新建实体类 AuthorInfo.java
1 package com.jike.book.pojo; 2 3 public class AuthorInfo { 4 5 private int id; 6 private UserInfo userInfo; 7 private String realname; 8 private int age; 9 public int getId() { 10 return id; 11 } 12 public void setId(int id) { 13 this.id = id; 14 } 15 public UserInfo getUserInfo() { 16 return userInfo; 17 } 18 public void setUserInfo(UserInfo userInfo) { 19 this.userInfo = userInfo; 20 } 21 public String getRealname() { 22 return realname; 23 } 24 public void setRealname(String realname) { 25 this.realname = realname; 26 } 27 public int getAge() { 28 return age; 29 } 30 public void setAge(int age) { 31 this.age = age; 32 } 33 34 35 }
在map包中创建author.xml的映射xml文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 3 4 <!DOCTYPE mapper 5 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 6 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 7 8 <mapper namespace="/"> 9 10 <insert id="insert_toauthor" parameterType="AuthorInfo"> 11 insert into author (id,realname,age) values(#{userInfo.id},#{realname},#{age}) 12 </insert> 13 14 </mapper>
在MyBatisConfig.xml文件中添加:
<typeAlias alias="AuthorInfo" type="com.jike.book.pojo.AuthorInfo"/>
以及
<mapper resource="com/jike/book/map/author.xml"/>
创建测试类:
1 package com.jike.book.test; 2 3 import java.io.Reader; 4 import java.util.List; 5 6 import org.apache.ibatis.io.Resources; 7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 10 11 import com.jike.book.pojo.AuthorInfo; 12 import com.jike.book.pojo.UserInfo; 13 14 public class Test8 { 15 16 public static void main(String[] args) { 17 String resource = "com/jike/book/map/MyBatisConfig.xml"; 18 Reader reader = null; 19 SqlSession session = null; 20 try{ 21 reader = Resources.getResourceAsReader(resource); 22 }catch(Exception e){ 23 e.printStackTrace(); 24 } 25 SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader); 26 session = sqlMapper.openSession(); 27 28 try{ 29 UserInfo u = new UserInfo(); 30 u.setUserName("uvi"); 31 u.setPassword("uvi"); 32 session.insert("insert", u); 33 34 AuthorInfo au = new AuthorInfo(); 35 au.setAge(23); 36 au.setUserInfo(u); 37 au.setRealname("pol"); 38 session.insert("insert_toauthor", au); 39 session.commit(); 40 }catch(Exception e){ 41 e.printStackTrace(); 42 session.rollback();//如果失败,则事务回滚 43 }finally{ 44 session.close(); 45 } 46 } 47 48 }
执行成功。