High-performance Java Persistence.pdf !link! Direct
Use stateless sessions for batch processing, or periodically flush() and clear() the Persistence Context to detach entities that are no longer needed.
Her first instinct was to blame the database. "Stupid Postgres," she muttered. But the query logs told a different story. The database was fine. It was her code that was the problem. High-performance Java Persistence.pdf
Transactions and locking
Recommended reading path
Use Bulk Updates .