我正在使用Hibernate中的Many-To-One编写程序,当我在DAO中编写以下代码时:
sessionFactory = HibernateUtility.createSessionFactory();
session = sessionFactory.openSession();
PatientEntity patientEntity=new PatientEntity();
DoctorEntity doctorEntity=(DoctorEntity) session.get(DoctorEntity.class, doctorId);
System.out.println(doctorEntity);
if (doctorEntity!= null)
{
System.out.println("hello");
patientEntity.setId(patient.getId());
patientEntity.setName(patient.getName());
patientEntity.setAge(patient.getAge());
patientEntity.setPhoneNumber(patient.getPhoneNumber());
patientEntity.setDoctor(doctorEntity);
}
session.getTransaction().begin();
session.persist(patientEntity);
session.getTransaction().commit();t the
我得到以下异常:
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): entity.PatientEntity
我的实体课程:
@Entity
@Table(name="Doctor")
public class DoctorEntity {
@Id
@Column(name="id")
private String id;
private String name;
private String phoneNumber;
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@Entity
@Table(name="Patient")
public class PatientEntity {
@Id
private Integer id;
private String name;
private String phoneNumber;
private Integer age;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="id",unique=true,insertable=false,updatable=false)
private DoctorEntity doctor;
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 String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public DoctorEntity getDoctor() {
return doctor;
}
public void setDoctor(DoctorEntity doctor) {
this.doctor = doctor;
}
}
我通过不同的链接,但无法将我的问题与它相关联。 Hibernate Many-To-One Relationship without Primary Key or Join Table
Repeated column in mapping for entity (should be mapped with insert="false" update="false")
Another Repeated column in mapping for entity error
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity
感谢任何帮助!
答案 0 :(得分:3)
您可能需要指定@GeneratedValue(strategy=GenerationType.AUTO)
或使用自己的自定义生成器。
答案 1 :(得分:0)
您需要在 Patient 类中使用您选择的生成策略指定 @GeneratedValue Annotation。