JPA OneToMany - 集合为空 [英] JPA OneToMany - Collection is null

查看:23
本文介绍了JPA OneToMany - 集合为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JPA 建立双向关系.我了解维护双方关系是应用程序的责任.

I'm trying to set up a bidirectional relationship using JPA. I understand that it's the responsability of the application to maintain both sides of the relationship.

例如,图书馆有多本书.在图书馆实体我有:

For example, a Library has multiple Books. In the Library-entity I have:

@Entity
public class Library {
  ..
  @OneToMany(mappedBy = "library", cascade = CascadeType.ALL)
  private Collection<Book> books;

  public void addBook(Book b) {
    this.books.add(b);
    if(b.getLibrary() != this)
      b.setLibrary(this);
  }
  ..
}

图书实体是:

@Entity
public class Book {
  ..
  @ManyToOne
  @JoinColumn(name = "LibraryId")
  private Library library;

  public void setLibrary(Library l) {
    this.library = l;
    if(!this.library.getBooks().contains(this))
      this.library.getBooks().add(this);
  }
  ..
}

不幸的是,OneToMany 端的集合为空.例如,调用 setLibrary() 失败,因为 this.library.getBooks().contains(this) 导致 NullPointerException.

Unfortunately, the collection at the OneToMany-side is null. So for example a call to setLibrary() fails because this.library.getBooks().contains(this) results in a NullPointerException.

这是正常行为吗?我应该自己实例化集合(这看起来有点奇怪),还是有其他解决方案?

Is this normal behavior? Should I instantiate the collection myself (which seems a bit strange), or are there other solutions?

推荐答案

实体是 Java 对象.Java 的基本规则不会因为类上有一个 @Entity 注释而改变.

Entities are Java objects. The basic rules of Java aren't changed just because there is an @Entity annotation on the class.

因此,如果您实例化一个对象并且其构造函数没有初始化其中一个字段,则该字段将被初始化为 null.

So, if you instantiate an object and its constructor doesn't initialize one of the fields, this field is initialized to null.

是的,您有责任确保构造函数初始化集合,或者确保所有方法都处理字段的可空性.

Yes, it's your responsibility to make sure that the constructor initializes the collection, or that all the methods deal with the nullability of the field.

如果您从数据库中获取此实体的实例(使用 em.find()、查询或通过浏览附加实体的关联),则该集合永远不会为空,因为 JPA 将始终初始化该集合.

If you get an instance of this entity from the database (using em.find(), a query, or by navigating through associations of attached entities), the collection will never be null, because JPA will always initialize the collection.

这篇关于JPA OneToMany - 集合为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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