Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to inject EntityManager via setter in spring

 
Bobby Anderson
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to inject an entity manager into a spring bean using a setter but in my config I only have access to a object of type EntityManagerFactory

I want the following:


In my spring config I get the entity manager factory from JNDI:


So when I want to inject that entityManager into my spring bean I use the following:


Which calls the setter on my bean but I of course get an exception saying that I cannot set a type of EntityManger using a EntityManagerFactory type
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to inject the EntityManagerFactory, then in your methods call the getEntityManager() of the factory. This is needed because you can't create an EntityManager up front, with a Connection, and have your Repository hold on to it forever. This is bad resource holding. So it isn't possible for you to inject an EntityManager.

I hope that helps and makes sense. It is an extremely correct and best implementation to not allow you to inject an EntityManager.

Good Luck

Mark
 
Billy Vandory
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark Spritzler wrote:You need to inject the EntityManagerFactory, then in your methods call the getEntityManager() of the factory. This is needed because you can't create an EntityManager up front, with a Connection, and have your Repository hold on to it forever. This is bad resource holding. So it isn't possible for you to inject an EntityManager.

I hope that helps and makes sense. It is an extremely correct and best implementation to not allow you to inject an EntityManager.

Good Luck

Mark


Hi Mark, I was under the impression that the EM injected by spring or via the @PersistenceContext is a proxy only. I'm concerned now because in my code I
inject the EM via the @PersistenceContext annotation, managed by spring. Can you clarify? Do I need to change my code to inject a factory and grab the EM from the factory instead?

thanks...

billworth
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic