如何映射JPA中的自定义集合? [英] How to map custom collection in JPA?

查看:445
本文介绍了如何映射JPA中的自定义集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problems in mapping custom collection with JPA (Hiberante provider). For example when I am using object with attribute

List<Match> matches;

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

但如果我用列出匹配项替换

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 / code>。

You can, but you have to refer to it as one of the common collections - List or Set.

因此:

private List matches = new Matches();

为什么?因为Hibernate使代理到你的集合,以启用延迟加载,例如。因此,它创建 PersistentList PersistentSet PersistentBag 列表但不是匹配。所以,如果你想添加额外的方法到那个集合 - 好吧,你不能。

Why? Because Hibernate makes proxies to your collections to enable lazy loading, for example. So it creates PersistentList, PersistentSet and PersistentBag, which are List but aren't Matches. So, if you want to add additional methods to that collection - well, you can't.

查看这篇文章了解更多详情。

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

You have a solution, however. Don't use inheritance, use composition. You can, for example, add a method to your entity called getMatchesCollection() (in addition to the traditional getter), which looks like:

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

您的匹配类看起来像(使用 google集合' ForwardingList ):

And your Matches class would look like (using 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集合,只需自己定义 ForwardingList - 它调用底层 List

If you can't use google collections, simply define the ForwardingList yourself - it's calling all the methods of the underlying List

如果您不需要任何其他方法来操作结构,那么不要定义自定义集合。

If you don't need any additional methods to operate on the structure, then don't define a custom collection.

这篇关于如何映射JPA中的自定义集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆