nrofis
nrofis

Reputation: 9796

JPA Entity not updating until server restart

I have a ternary relationship in my database: User, Book and BookOrder. The JPA entities are defined like this:

class Book {
    @Id
    @Column(name = "ID")
    private Integer id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "book")
    private Collection<BookOrder> bookOrderCollection;
    ....
}

class User {
    @Id
    @Column(name = "ID")
    private Integer id;

    @OneToMany(mappedBy = "reader")
    private Collection<BookOrder> bookOrderCollection;
    ....
}

class BookOrder {
    @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")
    @ManyToOne
    private Book book;

    @PrimaryKeyJoinColumn(name = "READER_ID", referencedColumnName = "ID")
    @ManyToOne
    private User reader;
    ....
}

When I want to save, I just do this:

Book book = ...;
User reader = ...;
BookOrder order = new BookOrder();
order.setBook(book);
order.setReader(reader);
book.getBookOrderCollection().add(order);
reader.getBookOrderCollection().add(order);
book.setQuantity(book.getQuantity() - 1);
bookFacade.edit(book);

And BookFacade class is:

class BookFacade {
    public void create(Book entity) {
        getEntityManager().persist(entity);
        getEntityManager().flush();
    }

    public void edit(Book entity) {
        getEntityManager().merge(entity);
    }

    public void remove(Book entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public Book find(Object id) {
        return getEntityManager().find(Book.class, id);
    }
}

That works fine in that the book quantity is updated in the database and the BookOrder is inserted. However, the User's bookOrderCollection is not updated until the server is restarted (when I pull the reader from the database).

I want to avoid performing usersFacade.edit(reader) because it not safe to create two transactions for one operation. Instead, I added cascade = Cascade.ALL to the reader field in Order class, but it didn't solve the problem.

How can I make it work within one transaction?

Upvotes: 3

Views: 458

Answers (1)

mvera
mvera

Reputation: 946

@OneToMany(cascade = CascadeType.ALL, mappedBy = "book") is the inverse relation, not the direct one. Maybe adding CASCADE to the other side (@ManyToOne) of the relation would have a different effect.

Upvotes: 2

Related Questions