I have a simple Java app that inserts records into a table “A”, linking them to records in another table, “B” by reading the appropriate “B” record, setting a reference in “A”, and saving the “A” record. The problem I am having is that Hibernate is apparently holding onto every “B” record that it reads during the linking process, which eventually causes the program to run out of memory (heap space error).
I looked at a heap dump with JHAT and here are the offending classes. The top three are all Hibernate stuff, the fourth is my Hibernate/JPA managed entity class. The out of memory error occurs as it tries to instantiate another instance of GeoEntity, my “B” table entity:
134489 instances of class org.hibernate.engine.spi.EntityKey
67245 instances of class org.hibernate.engine.spi.EntityEntry
67245 instances of class org.hibernate.internal.util.collections.IdentityMap$IdentityKey
67244 instances of class com.electricgearbox.model.GeoEntity
I’ve gone through my code, and I’m pretty sure I’m not doing anything like setting references and then never clearing them. In fact I’m explicitly setting the two local references I use to null at the end of the loop.
So, has anyone run into this? I’m sure it’s a missing line of code or a setting I’ve forgotten, but Googling and reading the Hibernate docs have provided no obvious solutions. What would make Hibernate hold onto these references for no apparent reason?
All of those are cached behind Session / EntityManager. If you use Hibernate Session, you can use following:
Or their counterparts in EntityManager if develop agains JPA API: