java - Persisting association in batches with Hibernate -


i have message entity , recipient entity, former has unidirectional manytomany relationship latter, such (with boilerplate code removed):

@entity public class message {     @manytomany(fetch = fetchtype.lazy, cascade = cascadetype.persist)     @jointable(name = "message_recipient", joincolumns = @joincolumn(name = "message_id"), inversejoincolumns = @joincolumn(name = "recipient_id"))     private set<recipient> recipients; } 

now persist message database, want associate message many recipients, potentially many thousands. therefore want avoid keeping set of thousands of objects in memory, instead persist association in batches, such x recipients in memory @ time. idea following pseudo-ish code.

message message = new message(); set<recipient> recipients = first 500 recipients  while (recipients != null) {     message.setrecipients(recipients);     messagerepository.saveandflush(message);      if (there more recipients save) {         recipients = next 500 recipients     } else {         recipients = null;     } } 

my assumption/hope hibernate detect no changes had been done properties of message entity except recipients association, , due cascade type being set persist, new recipients added in addition recipients had been persisted. however, happens recipients persisted on each iteration, deleted on next iteration before persisting new associations. result associations last iteration of loop persisted database (because rest deleted after being inserted).

this approach might "hacking" hibernate in way it's not supposed used. how go persisting association in batches such keep x objects in memory @ time?

i using hibernate 4.3.8 spring mvc , spring data jpa.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -