我在使用 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
感谢您的关注!
最佳答案
您可以,但您必须将其称为常见集合之一 - List
或 Set
。
所以:
private List matches = new Matches();
为什么?例如,因为 Hibernate 对您的集合进行代理以启用延迟加载。因此它创建了 PersistentList
、PersistentSet
和 PersistentBag
,它们是 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/