我正在尝试将数据插入到Patient
表中,该表与Site
具有多对一关系。 Site
与Patient
有一对多的关系。
但是,我得到org.postgresql.util.PSQLException: ERROR: insert or update on table "patients" violates foreign key constraint "fk_427e3ubwhw8n7a4id3mmrmjgj"
Detail: Key (patient_id)=(31) is not present in table "sites".
我曾尝试创建一组患者,将我的患者添加到此集,创建一个站点对象,然后使用此对象设置患者。我不确定哪一部分出了问题。
Session session = this.getFactory().openSession();
Transaction transaction = null;
try{
transaction = session.beginTransaction();
Date parsedDob = Date.valueOf(dob);
Date parsedDateReg = Date.valueOf(dateReg);
Site site = new Site();
site.setSiteId(1);
IPatient p = new Patient();
p.setFirstName(firstName);
p.setLastName(lastName);
p.setDob(parsedDob);
p.setDateRegistered(parsedDateReg);
p.setSite(site);
Set<IPatient> patientSet = new HashSet<IPatient>();
patientSet.add(p);
site.setPatients(patientSet);
session.save(site);
session.save(p);
transaction.commit();
}catch(Exception e){
e.printStackTrace();
}
我的Patient.hbm.xml文件是:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
<class name="Patient" table="patients">
<id name="patientId" column="patient_id">
<generator class="sequence" />
</id>
<version name="version" column="version" />
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<property name="dob" column="dob" />
<property name="gender" column="gender" />
<property name="dateRegistered" column="date_registered" />
<many-to-one name="site" class="com.example.model.Site" not-null="true" />
<set name="visits" cascade="all">
<key column="visit_id" />
<one-to-many class="Visit" />
</set>
</class>
我的Site.hmx.xml是:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
<class name="Site" table="sites">
<id name="siteId" column="site_id">
<generator class="sequence" />
</id>
<version name="version" column="version" />
<property name="name" column="name" />
<set name="patients" cascade="all">
<key column="patient_id" />
<one-to-many class="Patient" />
</set>
</class>
My Patient.java
public class Patient implements IPatient{
private Integer version;
private Integer patientId;
private Set<IVisit> visits;
private Site site;
private String firstName;
private String lastName;
private Date dob;
private Gender gender;
private Date dateRegistered;
public Patient(){
}
}
我的Site.java
public class Site {
private Integer siteId;
private Integer version;
private Set<IPatient> patients;
private String name;
public Site(){
}
}
答案 0 :(得分:1)
在下面一行之后,您应该将您的站点对象保存到db;
site.setSiteId(1);
session.save(site);
之后,您可以将网站对象设置为患者;
p.setSite(site);