0

I am developing a Spring-Boot application using spring-boot-starter-data-jpa. I am not able to understand which annotation I should use for injecting EntityManager? @Autowired or @PersistenceContext

I know @PersistenceContext is a JPA annotation whereas @Autowired belongs to Spring. But internally how do they make a difference? I have already taken a look at this. But could not understand the exact reason.

Sam
  • 2,352
  • 4
  • 32
  • 45
  • possible duplicate https://stackoverflow.com/questions/31335211/autowired-vs-persistencecontext-for-entitymanager-bean – Toerktumlare May 28 '19 at 16:50
  • @ThomasAndolf Yes, its a duplicate and my question's description says that. Let me know if you can help me understand the concept. – Sam May 28 '19 at 16:59

1 Answers1

1

A datasource is source of data. This could be for example a database.

One option if you need multiple datasources is to define them in a persistence.xml file. Here you can define multiple and separate them by name.

@PersistenceContext will then give you more fine grain of what you want to inject. Here you can select which datasource by defined name. There are some other options too. https://docs.oracle.com/javaee/7/api/javax/persistence/PersistenceContext.html

If using @Autowire you are just injecting the available persistence context by bean name. If you have 2 or more persistence contexts this may fail because of ambiguity.

Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
  • Do you have a specific example wherein there are multiple data sources used in Spring Boot and PersistenceContext is used? Also what are the fine grained controls PersistenceContext offers compared to a EntityManager Autowired? – Sam May 28 '19 at 18:23
  • spring will not load a persistence.xml by default. You have to set it up manually. https://www.logicbig.com/tutorials/spring-framework/spring-orm/local-container-entity-manager-factory-bean.html configuring a persistence.xml is a science: https://thoughts-on-java.org/jpa-persistence-xml/ – Toerktumlare May 28 '19 at 21:41
  • Fine grained settings on @PersistanceContext can for example be defining if the context is transaction managed or extended-managed, which means should it be bound to the transaction or should it be bound to the lifecycle of the bean. https://stackoverflow.com/questions/2547817/what-is-the-difference-between-transaction-scoped-persistence-context-and-extend – Toerktumlare May 28 '19 at 21:42
  • today with microservices you hardly use persistence.xml anymore, its to clunky and verbose. – Toerktumlare May 28 '19 at 21:42
  • if you want to learn about how persistance works in java you should learn the persistance api in https://docs.oracle.com/javaee/6/tutorial/doc/bnbpy.html – Toerktumlare May 28 '19 at 21:44