java - Avoid ConstraintViolationException in JPA and OneToMany relationship when merge -
what want accomplish illustration below avoid constraint violation exception occurs when run following:
parent p = new parent(); set<child> children = new hashset<child>(); kid c = new child(); children.add(c); p.setchildren(children); entitymanager.merge(p); entitymanager.merge(p); how configure jpa accomplish effect? below classes.
@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() { homecoming id; } @onetomany(fetch = fetchtype.lazy, cascade = cascadetype.all, orphanremoval = true) @joincolumn(name = "parent_id") public set<child> getchildren() { homecoming children; } @override public boolean equals(object obj) { if (this == obj) homecoming true; if (obj == null) homecoming false; if (getclass() != obj.getclass()) homecoming false; parent other = (parent) obj; if (uri == null) { if (other.uri != null) homecoming false; } else if (!uri.equals(other.uri)) homecoming false; homecoming true; } @override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + ((uri == null) ? 0 : uri.hashcode()); homecoming result; } } @entity @table(name = "child", indexes = {uniqueconstraints = { @uniqueconstraint(columnnames = { "text" }) }) public class kid 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() { homecoming id; } @override public boolean equals(object obj) { if (this == obj) homecoming true; if (obj == null) homecoming false; if (getclass() != obj.getclass()) homecoming false; kid other = (child) obj; if (text == null) { if (other.text != null) homecoming false; } else if (!text.equals(other.text)) homecoming false; homecoming true; } @override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + ((text == null) ? 0 : text.hashcode()); homecoming result; } } i utilize postgres , hibernate jpa provider
java hibernate postgresql jpa one-to-many
No comments:
Post a Comment