@untold seal has a question:
If you use @ManyToOne and @OneToMany JPA annotation on two classes this doesn't mean it will automatically update both sides right
1 messages · Page 1 of 1 (latest)
@untold seal has a question:
If you use @ManyToOne and @OneToMany JPA annotation on two classes this doesn't mean it will automatically update both sides right
<@&987246399047479336> please have a look, thanks.
like
class Book {
@ManyToOne
private Bookshelf bookshelf;
public void setBookshelf(Bookshelf newBookshelf) {
this.bookshelf = newBookshelf;
}
}
class Bookshelf {
@OneToMany
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
books.add(book);
book.setBookshelf(book);
}
}
Detected code, here are some useful tools:
This is what basically everyone online says to do
but it seems like you can create an inconsitency if you ever call setBookshelf directly
Or if you have a Book that's already in a Bookshelf and you add it to another, that causes an issue too
updates will be reflected if the entities are persistent
if your Book is persistent, and you call setBookshelf, you will create a bookshelf record in the database when transaction commits
what issue?
Becuase the old bookshelf would still contain a reference to the book
obv not in the db
but in the actual objects references
it won't be reflected
unless you refresh them through db
I think the issue here is not specifying manually how the entities are joined
the book relationship should have a @JoinColumn
and bookshelf should have mappedBy
ignore the JPA aspect for now
I just mean the actual objects references will be incorrect
Book book1 = new Book();
Bookshelf bookshelf1 = new Bookshelf();
Bookshelf bookshelf2 = new Bookshelf();
bookshelf1.addBook(book1);
bookshelf2.addBook(book2);
Detected code, here are some useful tools:
regardless of what JPA annotations you use, this will make it so both bookshelfs "have" the book, which shouldn't be possible
but to avoid that you have to do a whole disgusting mess of code
So I'm assuming people just avoid doing that
because those entities are detached from persistence context
if you operate with attached entities only, it should be fine
Hibernate has caches and can return you a cached instance when you query it from a db
it also creates proxies for your entities which can do 3 billion things when you call getters/setters on them
Book book1 = new Book();
Bookshelf bookshelf1 = new Bookshelf();
Bookshelf bookshelf2 = new Bookshelf();
bookshelf1.addBook(book1);
bookshelf2.addBook(book1);
bookshelf1.getBooks()
Detected code, here are some useful tools:
Ok so assuming everything is in the persistence context here
are the changes reflected when we call getBooks?
what's book2?
where are you seeing book2?
I was under the impression it would not be so, but I'd be happy to be wrong
whats book, you only have book1 