【发布时间】:2014-02-26 07:10:03
【问题描述】:
我在尝试创建一对多关联时遇到以下错误
Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.hibernate.collection.internal.PersistentBag
这里是运行创建关联的代码
public void assignDoctorSpecialty(Doctor doctor, Specialty specialty) {
Session session = sessionFactory.openSession();
session.beginTransaction();
doctor.setSpecialty(specialty);
List<Doctor> doctors = specialty.getDoctors();
doctors.add(doctor);
session.save(doctors);
session.getTransaction().commit();
session.close();
}
这是我的医生课
package edu.cs157b.hibernate;
import java.util.ArrayList;
import javax.persistence.*;
@Entity
@Table(name="DOCTOR_INFO")
@NamedQueries (
{
@NamedQuery(name = "Doctor.getAll", query = "from Doctor"),
@NamedQuery(name = "Doctor.findByName", query = "from Doctor where name = :name")
}
)
public class Doctor implements Person {
private int id;
private String name;
private Specialty specialty;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(unique=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne (fetch = FetchType.EAGER, cascade= CascadeType.PERSIST)
@JoinColumn(name="specialty_id")
public Specialty getSpecialty() {
return specialty;
}
public void setSpecialty(Specialty specialty) {
this.specialty = specialty;
}
}
这是我的专业课程
package edu.cs157b.hibernate;
import java.util.ArrayList;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="SPECIALTY_INFO")
@NamedQueries (
{
@NamedQuery(name = "Specialty.getAll", query = "from Specialty"),
@NamedQuery(name = "Specialty.findByName", query = "from Specialty where name = :name")
}
)
public class Specialty {
private List<Doctor> doctors = new ArrayList<Doctor>();
private int id;
private String name;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(unique=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy="specialty", targetEntity = Doctor.class,
fetch=FetchType.LAZY, cascade= CascadeType.PERSIST)
public List<Doctor> getDoctors() {
return doctors;
}
public void setDoctors(List<Doctor> doctors) {
this.doctors = doctors;
}
}
编辑
如果我直接保存Doctor 对象,而不是尝试通过级联保存Specialty 医生列表来间接保存它,它不会引发错误。但是,当我进入我的数据库时,Doctor 表中的specialty_id 没有设置。
【问题讨论】:
-
试试 CascadeType.ALL
标签: java eclipse hibernate jpa