JPA OneToMany - Collection为null [英] JPA OneToMany - Collection is null

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

问题描述

我正在尝试使用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端为null。因此,例如对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(),查询或通过附加实体的关联导航),该集合将永远不会为null,因为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 - Collection为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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