I have written a very basic and naive oneToMany relationship between a ChatComponent and its Chat Messages like this:
@OneToMany
List<ChatMessage> chatMessages;
This basically works, i.e., doing something like:
ChatMessage chatMessage = vo.toDomainObject();
chatMessage.setDate(new Date());
//Add the message to the chat component
em.getTransaction().begin();
em.persist(chatMessage);
chat.addChatMessage(chatMessage);
em.persist(chat);
em.getTransaction().commit();
gets the job done. Only, looking at the SQL logs, I can see that every time, the entire collection of chat messages is persisted again. That's obviously something I can't afford, given chat messages could quickly add up in the thousands.
The SQL that gets repeated for each chat message is as follows:
Hibernate: insert into BaseComponent_ChatMessage (BaseComponent_id, chatMessages_id) values (?, ?)
preceded by:
Hibernate: delete from BaseComponent_ChatMessage where BaseComponent_id=?
From this I conclude that Hibernate doesn't have a way to know that we're not dealing with a whole set of new objects and that it should keep those it already has.
I'm sure there is a way to add (and persist) only one member of the many side of a relationship, but I can't seem to find out how.