Given an entity with an embedded id and a recursive parent/child relationship, when querying a child instance with a join fetch to the parent, the child instance is populated with values that belongs to the parent instance. Domain model
@Entity(name = "OrganizationWithEmbeddedId")
public static class OrganizationWithEmbeddedId {
@EmbeddedId
private OrganizationId id;
private String name;
@ManyToOne
private OrganizationWithEmbeddedId parent;
@OneToMany(mappedBy = "parent")
private Set<OrganizationWithEmbeddedId> children;
public OrganizationWithEmbeddedId() {
}
public OrganizationWithEmbeddedId(OrganizationId id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public OrganizationWithEmbeddedId getParent() {
return parent;
}
public void setParent(OrganizationWithEmbeddedId parent) {
this.parent = parent;
}
public Set<OrganizationWithEmbeddedId> getChildren() {
return children;
}
public void addChild(OrganizationWithEmbeddedId child) {
if (children == null) {
children = new HashSet<>();
}
children.add(child);
child.setParent(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrganizationWithEmbeddedId that = (OrganizationWithEmbeddedId) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
@Embeddable
public static class OrganizationId implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "id")
private long value;
OrganizationId() {
super();
}
OrganizationId(long value) {
this.value = value;
}
@Override
public String toString() {
return Long.toString(value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrganizationId that = (OrganizationId) o;
return value == that.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
Query
Result The name property of the child instance is wrong. It has the value from the parent instance. |