JPA OneToMany - Collection is null

前端 未结 3 1077
长发绾君心
长发绾君心 2021-01-13 06:52

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.

相关标签:
3条回答
  • 2021-01-13 07:10

    It seems that books type of Collection in Library class is not initilized. It is null;

    So when class addBook method to add a book object to collection. It cause NullPointerException.

    @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);
     }
    

    Initilize it and have a try.

    Change

    private Collection<Book> books;
    

    To

    private Collection<Book> books = new ArrayList<Book>();
    
    0 讨论(0)
  • 2021-01-13 07:16

    Try to set the fetch type association property to eager on the OneToMany side. Indeed, you may leave this part (this.library.getBooks().add(this)) to be written within a session:

    Library l = new Library();    
    Book b = new Book();
    b.setLibrary(l);
    l.getBooks().add(b);
    
    0 讨论(0)
  • 2021-01-13 07:21

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题