Java 合并时避免JPA和OneToMany关系中的ConstraintViolationException
我想通过下面的示例实现的是避免出现约束冲突异常 运行以下命令时:Java 合并时避免JPA和OneToMany关系中的ConstraintViolationException,java,hibernate,postgresql,jpa,one-to-many,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以实现此效果?下面是课程 @
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提供程序我不知道您使用的是哪个hibernate版本,但在版本4.3.5之前,@OneToMany注释上的fetch=FetchType.LAZY仍然存在问题。并且仅适用于@LazyCollectionLazyCollectionType.TRUE hibernate等效项在我的配置中,我有class=org.springframework.orm.jpa.vendor.hibernatejbavendorapter,spring orm的版本是4.0.4-RELEASE。根据这个链接,应该是Hibernate4.3.5-Final——我当然想用JPA,而不是Hibernate。