@PersistenceUnit injects an instance of EntityManagerFactory (used for creating EntityManagers)
...quite confusing when you first encounter them.
They both share the unitName parameter attribute.. which identifies the persistence unit. You'd typically use EntityManagerFactory only when you intend to manage the life-cycle of your EntityManagers... but generally, you're better of just injecting a container managed EntityManager using the @PersistenceContext
[corrected error: Thanks Niranjan, that was a copy and paste error. fixed it now]
To add on that, @PersistenceUnit is typically used for Java SE. Correct me if I am wrong!
In J2SE, who is going to inject the reference ? @PersistenceUnit can only be used in a J2EE environment. In J2SE, you have to use Persistence.createEntityManagerFactory instead.
so in nutshell we can say that in case of @PersistenceUnit developer needs to worry about releasing the resources acquired by EntityManager and in case of @PersistenceContext container do this for us.
yes.. basically that. and you can explicity join a container-managed JTA transaction like this:
EntityManagers you get via @PersistenceContext are typically called Container Managed Entity Manager because the container manages things for you.
while EntityManagers you get via @PersistenceUnit / entityManagerFactory.createEntityManager() are called Application Managed Entity Manager because you'd have to manage certain things in your application code.