在处理继承时,我遇到了休眠中延迟加载的问题。我有一个实体引用了第二个子类实体。我希望引用延迟加载,但这会导致我的 .equals() 方法出错。
在下面的代码中,如果在 A 的实例上调用 equals(),则在检查 Object o 是否是 C 的实例时,C.equals() 函数中的检查失败。它失败是因为另一个对象实际上是 Hibernate由 javassist 创建的代理,它扩展了 B,而不是 C。
我知道 Hibernate 不能在不访问数据库的情况下创建 C 类型的代理,从而破坏延迟加载。有没有办法让 A 类中的 getB() 函数返回具体的 B 实例而不是代理(懒惰地)?我尝试在 getB() 方法上使用 Hibernate 特定的 @LazyToOne(LazyToOneOption.NO_PROXY) 注释无济于事。
@Entity @Table(name="a")
public class A {
private B b;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="b")
public B getB() {
return this.b;
}
public boolean equals(final Object o) {
if (o == null) {
return false;
}
if (!(o instanceof A)) {
return false;
}
final A other = (A) o;
return this.getB().equals(o.getB());
}
}
@Entity @Table(name="b")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="type",
discriminatorType=DiscriminatorType.STRING
)
public abstract class B {
private long id;
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof B)) {
return false;
}
final B b = (B) o;
return this.getId().equals(b.getId());
}
}
@Entity @DiscriminatorValue("c")
public class C extends B {
private String s;
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (obj == null) {
return false;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof C)) {
return false;
}
final C other = (C) o;
if (this.getS() == null) {
if (other.getS() != null) {
return false;
}
} else if (!this.getS().equals(other.getS())) {
return false;
}
return true;
}
}
@Entity @DiscriminatorValue("d")
public class D extends B {
// Other implementation of B
}