Il diritto posto a guardare in la documentazione per questo tipo di trattamento è l'intero Chapter 13. Batch processing.
Qui, ci sono diversi errori evidenti nel vostro approccio attuale:
- Non si dovrebbe iniziare/commit della transazione per ogni aggiornamento.
è consigliabile attivare JDBC dosaggio e impostarlo su un numero ragionevole (10-50):
hibernate.jdbc.batch_size 20
si dovrebbe flush()
e poi clear()
la sessione a intervalli regolari (ogni n record dove n è pari a il parametro hibernate.jdbc.batch_size
) o continuerà a crescere e potrebbe esplodere (con un OutOfMemoryException
) ad un certo punto.
Di seguito, l'esempio dato nella sezione 13.2. Batch updates che illustra questo:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
ScrollableResults customers = session.getNamedQuery("GetCustomers")
.setCacheMode(CacheMode.IGNORE)
.scroll(ScrollMode.FORWARD_ONLY);
int count=0;
while (customers.next()) {
Customer customer = (Customer) customers.get(0);
customer.updateStuff(...);
if (++count % 20 == 0) {
//flush a batch of updates and release memory:
session.flush();
session.clear();
}
}
tx.commit();
session.close();
Si può anche considerare l'utilizzo della StatelessSession.
Un'altra opzione sarebbe quella di utilizzare DML-style operations (in HQL!): UPDATE FROM? EntityName (WHERE where_conditions)?
.In questo esempio l'UPDATE HQL:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery(hqlUpdate)
.setString("newName", newName)
.setString("oldName", oldName)
.executeUpdate();
tx.commit();
session.close();
Anche in questo caso, fare riferimento alla documentazione per i dati (in particolare come trattare con i valori version
o timestamp
proprietà utilizzando la parola chiave VERSIONED
).
fonte
2010-03-07 22:53:08
Forse significa veramente * N * Hibernate (nel titolo)? – M4N
Non per Java: NHibernate è per .NET. – duffymo
risolto il titolo grazie. – Blankman