divide by zero
divide by zero

Reputation: 2370

Entity is not updated after adding to collection some value

For example, I have entity User, which has many messages.

In this code, i get user and add to it's collection new message, then i flush the changes with simple : session.flush();

User activeUser = userDao.findById(userId);
                Set<Message> messages = activeUser.getMessages();
                messages.add(chatroomModel.getMessage());
                session.flush();

Later I wish to get all Messages by some criteria and every message has it's owner (user), but the for last inserted message there are no user.

I wish to notice that no commit is done and all logic is happening in same transaction. I am learning hibernate and trying to build some example project, so spring and other "cool" stuff is not used. Can you please help me with a tip - what i am doing wrong. Thanks.

Upvotes: 0

Views: 35

Answers (1)

Gab
Gab

Reputation: 8323

Message is the owner of the relationship here (it own the user id in the database table). ORM are not magic yet and still constraigned by the relationship model, you have to specify the user for the message before inserting it, in fact just add

Message m = chatroomModel.getMessage();
m.setUser(activeUser);
messages.add(m)

Upvotes: 2

Related Questions