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

标签 java hibernate collections jpa persistence

我在使用 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/

相关文章:

java - user.dir 属性在 OSX jdk 1.8.0_111 上损坏?其他操作系统、版本怎么样?

java - Servlet 映射 : url-pattern for URLs with trailing slash

java - JPA 中的参数化查询出现 "org.hibernate.QueryException: Unable to resolve path..."错误

java - Spring3/Hibernate断言失败

java - arraylist java上的程序

java - SocketTimeoutException 和 Jetty 的问题

java - RMI:远程对象的字段是否被序列化并发送到客户端?

java - 如何覆盖策略 GenerationType.TABLE 的 Hibernate Id 生成

Java PriorityQueue<Integer> 未按预期排序

wpf - 如何将 List 作为 ItemSource 绑定(bind)到 XAML 中的 ListView?