Hi,
I have the following POJO
Code:
@Entity @Table(name="organization")
public class Organization implements Serializable {
private List<Organization> children = new ArrayList<Organization>();
private List<String> parentsIds = new ArrayList<String>();
@ElementCollection(targetClass=String.class, fetch=FetchType.LAZY)
@JoinTable(name="organization_hierarchy",joinColumns=@JoinColumn(name="child_id"))
@Column(name="parent_id")
public List<String> getParentsIds() {
return parentsIds;
}
@ManyToMany(cascade={}, fetch=FetchType.LAZY)
@JoinTable(name="organization_hierarchy",
joinColumns = {
@JoinColumn(name="parent_id", unique=false, nullable=false, insertable=true, updatable=false) },
inverseJoinColumns = {
@JoinColumn(name="child_id", unique=false, nullable=false, insertable=true, updatable=false) })
public List<Organization> getChildren() {
return children;
}
...
}
So records in table "
organization" has tree hierarchy using table "
organization_hierarchy"
Before migration to 3.6.1 and annotations, the following code (adding new Organization to the hierarchy) worked fine:
Code:
child.getParentsIds().add(parent.getId());
parent.getChildren().add(child);
But now it throws java.sql.SQLException
Violation of PRIMARY KEY constraint 'PK_organization_hierarchy'. Cannot insert duplicate key in object 'dbo.organization_hierarchy'.As far as I understand, it tries to insert 2 records into organization_hierarchy with the same mapping (one for
child.getParentsIds().add(parent.getId()) and one for
parent.getChildren().add(child))
Removing
child.getParentsIds().add(parent.getId() resolves the issue, but there are many places in code with the same operations and also there are some places, when size/content of
child.getParentsIds() is checked after such adding. So commenting
child.getParentsIds().add(parent.getId()) out requires re-factoring all related code.
It is possible to prevent insertion the second record using annotations? (how to make
child.getParentsIds() read-only) ?