合并时避免JPA和OneToMany关系中的ConstraintViolationException

时间:2014-06-24 12:09:41

标签: java hibernate postgresql jpa one-to-many

我想通过以下示例实现的目的是避免发生的约束违规异常 运行以下内容时:

Parent p = new Parent();
Set<Child> children = new HashSet<Child>();
Child c = new Child();
children.add(c);
p.setChildren(children);

entityManager.merge(p);
entityManager.merge(p);

如何配置JPA来实现此效果?以下是课程。

@Entity
@Table(name = "parent", indexes = {uniqueConstraints = { @UniqueConstraint(columnNames = { "uri" }) })
public class Parent implements Serializable {
  ...
  private String uri;
  private Set<Child> children = new HashSet<Child>();


  @Id
  @Column(name = "id", unique = true)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parent_seq")
  @SequenceGenerator(name = "parent_seq", sequenceName = "parent_seq", allocationSize = 1)
  public Long getId() {
    return id;
  }

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "parent_id")
  public Set<Child> getChildren() {
    return children;
  }

@Override
  public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Parent other = (Parent) obj;
        if (uri == null) {
            if (other.uri != null)
                return false;
        } else if (!uri.equals(other.uri))
            return false;
        return true;
    }


@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((uri == null) ? 0 : uri.hashCode());
        return result;
    }



}

@Entity
@Table(name = "child", indexes = {uniqueConstraints = { @UniqueConstraint(columnNames = { "text" }) })
public class Child implements Serializable {

  private String text;

  @Id
  @Column(name = "id", unique = true)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "child_seq")
  @SequenceGenerator(name = "child_seq", sequenceName = "child_seq", allocationSize = 1)
  public Long getId() {
    return id;
  }



  @Override
  public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Child other = (Child) obj;
        if (text == null) {
            if (other.text != null)
                return false;
        } else if (!text.equals(other.text))
            return false;
        return true;
    }


@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((text == null) ? 0 : text.hashCode());
        return result;
    }
}

我使用postgres和hibernate作为JPA提供程序

0 个答案:

没有答案