我有以下两个类(实体)。
人类
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue(strategy= GenerationType.SEQUENCE,
generator="person_id_seq")
@SequenceGenerator(name="person_id_seq", sequenceName="person_id_seq",
allocationSize=1)
private Integer person_id;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinColumn(name = "location_id")
private Location location;
}
位置类
@Entity
@Table(name = "location")
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "location_seq_gen")
@SequenceGenerator(name = "location_seq_gen", sequenceName = "location_id_seq", allocationSize = 1)
@Column(name = "location_id")
private Long id;
@Column(name = "address_1")
private String address1;
@Column(name = "address_2")
private String address2;
@Column(name = "city")
private String city;
@Column(name = "state")
private String state;
@Column(name = "zip")
private String zipCode;
@Column(name = "location_source_value")
private String locationSourceValue;
public Location() {
}
public Location(String address1, String address2, String city, String state, String zipCode) {
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
public Long getId() {
return id;
}
public Long getId(String address1, String address2, String city, String state, String zipCode){
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getLocationSourceValue() {
return locationSourceValue;
}
public void setLocationSourceValue(String locationSourceValue) {
this.locationSourceValue = locationSourceValue;
}
}
我希望能够做到以下几点:- 当我插入一个新的人员记录时,我会提供addressLine1、addressLine2、city、state、zipcode等信息,它应该在Location表中检查记录是否存在。如果存在,则从Location表获取location_id,并使用现有的location_id插入新的Person记录。如果不存在,则在Location表中创建一个新记录,获取location_id,并将其用作新的Person记录的location_id。
我相信这可以通过适当的JPA Hibernate注释实现。
目前,每当我插入一个新的Person记录时,即使Location已经存在,它也会在Location表中创建一个新的记录。
请帮忙解决。谢谢!