gpt4 book ai didi

java - 如何在 JPA 中映射自定义集合?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:49 25 4
gpt4 key购买 nike

我在使用 JPA(Hiberante 提供程序)映射自定义集合时遇到问题。例如当我使用带有属性的对象时

List<Match> matches;

<one-to-many name="matches">
<cascade>
<cascade-all />
</cascade>
</one-to-many>

在我的ORM文件中,没问题;但是,如果我将 "List matches;" 替换为

private Matches matches;

,其中“匹配”定义如下:

public class Matches extends ArrayList<Match> {

private static final long serialVersionUID = 1L;
}

它产生以下错误:

Caused by: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: by.sokol.labs.jpa.MatchBox.matches

感谢您的关注!

最佳答案

您可以,但您必须将其称为常见集合之一 - ListSet

所以:

private List matches = new Matches();

为什么?例如,因为 Hibernate 对您的集合进行代理以启用延迟加载。因此它创建了 PersistentListPersistentSetPersistentBag,它们是 List 但不是 Matches。因此,如果您想向该集合添加其他方法 - 嗯,您不能。

Check this article了解更多详情。

但是,您有一个解决方案。不要使用继承,使用组合。例如,您可以向名为 getMatchesCollection() 的实体添加一个方法(除了传统的 getter 之外),它看起来像:

 public Matches getMatchesCollection() {
return new Matches(matches);
}

你的 Matches 类看起来像(使用 google-collections ' ForwardingList):

public class Matches extends ForwardingList {
private List<Match> matches;
public Matches(List<Match> matches) { this.matches = matches; }
public List<Match> delegate() { return matches; }
// define your additional methods
}

如果您不能使用 google collections,只需自己定义 ForwardingList - 它会调用底层 List 的所有方法

如果您不需要任何额外的方法来操作该结构,则不要定义自定义集合。

关于java - 如何在 JPA 中映射自定义集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3174379/

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