在实际程序开发中,经常需要持久化临时对象,比如新建一个学生,将加入到一个存在的班级中(或者新建的一个班级),在这里不妨把引起级联操作的对象称为根对象(本文中所指的就是team对象) ,而根对象可能出于transient,persistence,detach三态,下面分别讨论
首先,建立数据库表:
CREATE TABLE certificate (
id varchar ( 100 ) NOT NULL default '' ,
description varchar ( 100 ) default '' ,
PRIMARY KEY (id)
);
CREATE TABLE student (
team_id varchar ( 100 ) default '' ,
id varchar ( 100 ) NOT NULL default '' ,
name varchar ( 20 ) default '' ,
cardId varchar ( 20 ) NOT NULL default '' ,
age int ( 11 ) default ' 0 ' ,
PRIMARY KEY (id)
);
CREATE TABLE team (
id varchar ( 100 ) NOT NULL default '' ,
teamName varchar ( 100 ) default '' ,
PRIMARY KEY (id)
);
INSERT INTO certificate VALUES ( ' 1 ' , ' 110108 ' );
INSERT INTO certificate VALUES ( ' 2 ' , ' 110109 ' );
INSERT INTO student VALUES ( ' 1 ' , ' 1 ' , ' tomclus ' , ' 2006m ' , 33 );
INSERT INTO student VALUES ( ' 2 ' , ' 2 ' , ' tom ' , ' 2007m ' , 22 );
INSERT INTO team VALUES ( ' 1 ' , ' team1 ' );
持久化对象Pojo
package Cascade.Relation;
public class Certificate {
private String id;
private String description;
private Student stu;
public Student getStu() {
return stu;
}
public void setStu(Student stu) {
this .stu = stu;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this .description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this .id = id;
}
}
package Cascade.Relation;
public class Student {
private String id; // 标识id
private String cardId; // 学号
private String name; // 学生姓名
private int age; // 岁数
private Certificate cer; // 身分证
private Team team; // 班级
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getCardId() {
return cardId;
}
public void setId(String id) {
this .id = id;
}
public void setAge( int age) {
this .age = age;
}
public void setName(String stuName) {
this .name = stuName;
}
public void setCardId(String cardId) {
this .cardId = cardId;
}
public String getId() {
return id;
}
public Student() { // 无参的构造函数
}
public Certificate getCer() {
return cer;
}
public void setCer(Certificate pass) {
this .cer = pass;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this .team = team;
}
}
package Cascade.Relation;
import java.util.HashSet;
import java.util.Set;
public class Team {
private String id;
private Set students = new HashSet();
private String teamName;
private Set tests;
public Set getTests() {
return tests;
}
public void setTests(Set tests) {
this .tests = tests;
}