Creating effective jpa oneToMany relationships?

I wrote a very basic and naive OneToMany relationship between ChatComponent and its chat messages, such as:

@OneToMany
List<ChatMessage> chatMessages;

This basically works, i.e. does 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();

doing his job. Just looking at the SQL logs, I see that every time the entire collection of chat messages is saved again. This is obviously something that I cannot afford, given that chat messages can add up quickly in thousands.

The SQL that is repeated for each chat message is as follows:

Hibernate: insert into BaseComponent_ChatMessage (BaseComponent_id, chatMessages_id) values (?, ?)

preceded:

Hibernate: delete from BaseComponent_ChatMessage where BaseComponent_id=?

From this I conclude that Hibernate does not know that we are not dealing with a whole set of new objects and that it should contain those that it already has.

, ( ) , , .

+3
2

, , , .

@OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE}, fetch=FetchType.LAZY, mappedBy="parent")
List<ChatMessage> chatMessages;

@ManyToOne
@JoinColumn(name="OWNER_CHAT_COMPONENT_ID", nullable=false)
private ChatComponent parent;

addChatMessage , , .

    em.getTransaction().begin();
    chat.addChatMessage(chatMessage);
    em.persist(chat);
    em.getTransaction().commit();
+2

hashCode equals ChatMessage, Hibernate , .

IDE hashCode() equals(). Eclipse > "" > " -" "" @Id .

cascade=CascadeType.ALL @OneToMany

+1

Source: https://habr.com/ru/post/1723857/


All Articles