gpt4 book ai didi

java - 通过接口(interface)的惰性代理(具有 final方法的实体)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:33 24 4
gpt4 key购买 nike

我在我的项目中有一个要求,即我的所有方法都应该是抽象的或最终的(请不要争论这个要求——我知道它很愚蠢,只是假设它在那里)。

这是 Hibernate 映射实体的一个问题,因为 Hibernate 需要在运行时创建代理,以便能够在延迟加载时初始化关系。无法覆盖 setter 方法会导致根本无法加载这些方法(确实执行了查询,但从未填充对象)。

Hibernate's documentation 中所述:

If the final class does implement a proper interface, you could alternatively tell Hibernate to use the interface instead when generating the proxies. See Example 4.4, “Proxying an interface in hbm.xml” and Example 4.5, “Proxying an interface in annotations”.

例子:

 @Entity @Proxy(proxyClass=ICat.class) public class Cat implements ICat { ... }

因此理论上可以只告诉 hibernate 实现一个接口(interface)而不是扩展原始类。

我试过这个解决方案,但我的问题出在关系本身。这是一个过度简化的示例:

@Entity
@Proxy(proxyClass = ICat.class)
@Table(name = "cat")
public class Cat implements ICat {

@Id
private Long catId;

@OneToMany(mappedBy = "cat", fetch = FetchType.LAZY)
private List<Kitten> kittens;

...
}


@Entity
@Proxy(proxyClass = IKitten.class)
@Table(name="kitten")
public class Cat implements IKitten {

@Id
private Long kittenId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="catId")
private Cat cat;

...
}

现在,如果我尝试获取一个 Cat 对象,我会得到一个 ClassCastException,因为它试图将一个 IKitten 集合转换为一个 小猫 集合。这让我认为我应该使用接口(interface)而不是实现来声明关系——这也会产生编译时错误,因为我的接口(interface)从未被声明为实体,但实现是(这在文档的示例中有明确说明)。

我该如何解决这个问题?

最佳答案

您可以在一对多多对一 关联中使用该接口(interface),但您需要在 中提供实际的类targetEntity 属性。关系应该是这样的:

@Entity
@Proxy(proxyClass = ICat.class)
@Table(name = "cat")
public class Cat implements ICat {

@Id
private Long catId;

@OneToMany(mappedBy = "cat", fetch = FetchType.LAZY, targetEntity=Cat.class)
private List<IKitten> kittens;

...
}


@Entity
@Proxy(proxyClass = IKitten.class)
@Table(name="kitten")
public class Cat implements IKitten {

@Id
private Long kittenId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="catId", targetEntity=Cat.class)
private ICat cat;

...
}

关于java - 通过接口(interface)的惰性代理(具有 final方法的实体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28495606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com