当我获取一个类似于另一个实体的“父”实体时,我有一个奇怪的行为。这些是我的实体类:
父实体(“一侧”)
package so.lazy;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
@Entity
public class Parent extends Base {
private static final long serialVersionUID = -1111542804002616234L;
@OneToMany(mappedBy = "one")
private Set<Child> children = new LinkedHashSet<Child>();
// more fields
public Set<Child> getChildren() {
return children;
}
public void setChildren(Set<Child> children) {
this.children = children;
}
@Override
public String toString() {
return "Parent{" +
"dataId=" + getDataId() +
'}';
}
// more getters and setters
}
子实体(“多面”)
package so.lazy;
import javax.persistence.*;
@Entity
public class Child extends Base {
private static final long serialVersionUID = -8798542804002616234L;
@ManyToOne(fetch = FetchType.LAZY)
private Parent parent;
// more fields
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
// more getters and setters
}
抽象基类
package so.lazy;
import java.io.Serializable;
import java.util.UUID;
import javax.persistence.*;
import org.hibernate.annotations.Type;
@MappedSuperclass
public abstract class Base implements Serializable {
@Id
@Column(name = "data_id")
@Type(type = "pg-uuid")
private java.util.UUID dataId;
public Base() {
dataId = UUID.randomUUID(); // production: com.fasterxml.uuid.generators UUID Type 1
}
public UUID getDataId() {
return dataId;
}
public void setDataId(UUID dataId) {
this.dataId = dataId;
}
}
使用此代码时:
Child child=childrepository.findOne(uuid);
Parent parent=child.getParent();
System.out.println("Parent: " + parent.toString()); // Output A
System.out.println("ID in parent: " + parent.getDataId); // Output B
输出为输出A和B中的父级包含两个完全不同的UUID 。
方法Parent#toString()
给出正确的UUID,getter给出错误的UUID。
为什么?
如果我在@ManyToOne(fetch = FetchType.EAGER)
中将parent
的{{1}}切换到Child
,则可以正常工作。
我的依赖项:
春天4.3.8
Spring DataJPA 1.11.0
PostgreSQL 9.4-1202-jdbc42