http://bigcat.easymorse.com/?p=249
在EJB3.0 规范中 多对一与一对多的双向关系, 多对一(就是@ManyToOne注解的这端,是多端哦 不要搞混了)这端总是双向关联端的主题(owner)端, 而一对多端的关联注解为 @OneToMany(mappedBy=" " )其值是:多对一端的属性
实例三: (一对多)
CREATE TABLE "ABC"."CLAZZ"
( "ID" NUMBER(*,0) NOT NULL ENABLE,
"CLASSNAME" VARCHAR2(20 BYTE),
CONSTRAINT "CLAZZ_PK" PRIMARY KEY ("ID"))
CREATE TABLE "ABC"."STUDENT"
( "ID" NUMBER(*,0) NOT NULL ENABLE,
"NAME" VARCHAR2(20 BYTE),
"BIRTHDAY" DATE,
"CLAZZID" NUMBER(*,0),
CONSTRAINT "PK_STUDENT" PRIMARY KEY ("ID"))
alter table STUDENT
add constraint student_clazz_fk foreign key
(clazzid) references CLAZZ (id)
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
@Table(name="clazz")
public class Clazz {
@Id
@GeneratedValue(generator="cseq")
@GenericGenerator(name="cseq",strategy="sequence",parameters={@Parameter(name="sequence",value="clazz_seq")})
private Integer id;
private String className;
@OneToMany(cascade=CascadeType.REFRESH,mappedBy="clazz")//一个班级有很多学生
private Set<Student> students;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
public class Student {
@Id
@GeneratedValue(generator="sseq")
@GenericGenerator(name="sseq",strategy="sequence",parameters={@Parameter(name="sequence",value="seq_student")})
private Integer id;
private String name;
private Date birthday;
@ManyToOne
@JoinColumn(name="clazzid")
private Clazz clazz; //和上面的红色的clazz对应
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
}
在delete Clazz的一个对象的时候,出现异常:
Caused by: java.sql.BatchUpdateException: ORA-02292: 违反完整约束条件 (ABC.UC_CLAZZ_FK) - 已找到子记录
但是在Student表中没有和Clazz表有关联的行时可以删除
解决方法:@OneToMany(cascade={CascadeType.REFRESH,CascadeType.REMOVE},mappedBy="clazz") //添加删除级联