hibernate-annotation CascadeType.PERSIST不起作用的解决方法

有如下两个实体类 , Student和Grade 为多对一关系。

Student.java

 @Entity
public class Student {
private Integer id;
private String name;
private Grade grade;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
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;
}
@ManyToOne(cascade={CascadeType.PERSIST})
@JoinColumn(name="gradeid")
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
} }

Grade.java

 @Entity
public class Grade { private Integer id;
private String name; @Id
@GeneratedValue(strategy=GenerationType.AUTO)
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;
} }

可以看到Student类的grade属性已经设置了   @ManyToOne(cascade={CascadeType.PERSIST})

但只save Student对象时依然会报 org.hibernate.TransientObjectException 异常,如下:

public class Init {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction(); Grade g = new Grade();
g.setName("一班"); Student s = new Student();
s.setName("张三");
s.setGrade(g); session.save(s); session.getTransaction().commit(); }
}

运行结果:

Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: accp.hib.Grade

解决办法如下:

方法一:改用persist方法来保存

把session.save(s); 更改为 session.persist(s);

再次保存成功。

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Grade (name, id) values (?, ?)
Hibernate: insert into Student (gradeid, name, id) values (?, ?, ?)

方法二:使用hibernate的自定义的级联,不要使用jpa的

把Student类grade的注解改为hibernate的注解

@ManyToOne(cascade={CascadeType.PERSIST})
@JoinColumn(name="gradeid")

改为:

@ManyToOne

@JoinColumn(name="gradeid")

@Cascade(value={CascadeType.SAVE_UPDATE})

注意,这里的CascadeType和@Cascade都是org.hibernate.annotations包下的,所以把

import javax.persistence.CascadeType;

改为:import org.hibernate.annotations.CascadeType;

并加上:import org.hibernate.annotations.Cascade;

再次保存成功。

上一篇:Linux 设备驱动之 UIO 机制(基本概念)


下一篇:C# form表单提交enctype="multipart/form-data" 与 enctype="application/x-www-form-urlencoded" 两者之间的区别