I'm starting a new project and I'm totally new to JPA/Hibernate use. I'm trying to understand how to use EntityManager properly. More precisely, when to instantiate them, how many do I need, should I close them, should I put everything into transactions?
Anyway, in my current code, I got an org.hibernate.LazyInitializationException while trying to read an entity that I previously saved. I would understand the opposite (reading an antity in a transaction then trying to save the read entity in another transaction but since transaction is over, the entity is unmanaged so save fails), but this I can't understand.
I put my code on GitHub (https://github.com/GaetanLeu/intl), it's just a couple of classes. My main is in src/sandbox/MessageSandbox.java and it fails at line 28 with the following stacktrace:
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at entity.MessageKey_$$_jvstfcc_0.toString(MessageKey_$$_jvstfcc_0.java)
at java.lang.String.valueOf(String.java:2854)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at com.google.common.base.Present.toString(Present.java:88)
at java.lang.String.valueOf(String.java:2854)
at java.io.PrintStream.println(PrintStream.java:821)
at sandbox.MessageSandbox.main(MessageSandbox.java:28)
Also I got a warning from Hibernate saying my EntityManager already exists, what happens then? Is the EntityManagerFactory.createEntityManager method returning the existing one?
WARN: HHH000436: Entity manager factory name (intl) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
Really I'm lost about when to create EntityManagers ^^ Any help would be appreciated, but please simple explanation I'm really new to this.
Oh BTW, I want to precise I'm not using Spring, I don't have EJBs, I want to manipulate EntityManagers manually for now until I understand it. Thanks :)