JPA HIbernate - ManyToOne映射 - 如果不存在则插入

时间:2017-06-13 18:03:05

标签: java hibernate jpa

我有以下2个类(实体)。

人类

@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;
}

}

我希望能够做到以下几点。

  • 当我插入新的Person记录时,我将提供addressLine1,addressLine2,city,state,zipcode,如果记录存在,它应该在Location表中检查。如果存在,则从Location表中获取location_id,并使用现有location_id插入新的Person记录。如果它不存在,则在Location表中创建一个新记录,获取location_id并将其用作新Person记录的location_id。

我相信这可以通过适当的JPA Hibernate注释来实现。

目前,每当我插入新的Person记录时,即使该位置存在,它也会在Location表中创建一条新记录。

请帮忙。提前谢谢!

1 个答案:

答案 0 :(得分:0)

你是否覆盖了equals和hashCode方法?通过此方法,您将添加标识表中的每一行。您已正确指定注释,但Hibernate无法确定此行是否存在。内部Hibernate使用Map,所以equals和hashCode可以解决你的问题。