先来假设这样一个问题:如果数据库里面有一个用户表和一个作家表,那么当要添加一条数据到作家表中时,作家表的id必须是用户表中的其中一个id,因为作家一定也要是一个用户。这时就涉及到事务处理。
在上一篇博客的基础上,同时添加一个人的信息到用户表和作家表,如果失败则需要事务回滚
在pojo包中新建实体类 AuthorInfo.java
package com.jike.book.pojo; public class AuthorInfo { private int id;
private UserInfo userInfo;
private String realname;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} }
在map包中创建author.xml的映射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="/"> <insert id="insert_toauthor" parameterType="AuthorInfo">
insert into author (id,realname,age) values(#{userInfo.id},#{realname},#{age})
</insert> </mapper>
在MyBatisConfig.xml文件中添加:
<typeAlias alias="AuthorInfo" type="com.jike.book.pojo.AuthorInfo"/>
以及
<mapper resource="com/jike/book/map/author.xml"/>
创建测试类:
package com.jike.book.test; import java.io.Reader;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.jike.book.pojo.AuthorInfo;
import com.jike.book.pojo.UserInfo; public class Test8 { public static void main(String[] args) {
String resource = "com/jike/book/map/MyBatisConfig.xml";
Reader reader = null;
SqlSession session = null;
try{
reader = Resources.getResourceAsReader(resource);
}catch(Exception e){
e.printStackTrace();
}
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
session = sqlMapper.openSession(); try{
UserInfo u = new UserInfo();
u.setUserName("uvi");
u.setPassword("uvi");
session.insert("insert", u); AuthorInfo au = new AuthorInfo();
au.setAge();
au.setUserInfo(u);
au.setRealname("pol");
session.insert("insert_toauthor", au);
session.commit();
}catch(Exception e){
e.printStackTrace();
session.rollback();//如果失败,则事务回滚
}finally{
session.close();
}
} }
执行成功。