122

What is the difference between:

@Autowired
private EntityManager em;

versus:

@PersistenceContext
private EntityManager em;

Both options work in my application, but can I break something by using the @Autowired annotation?

7 Answers 7

66

You shouldn't use @Autowired. @Autowired normally would create just one bean of EntityManager to be used for the entire application. But we need a new EntityManager object for every communication (database transaction) with the database. In this communication we can make multiple actions: inserts, deletes, updates, reads, which need to happen under the same context (the persistence context) isolated from other similar contexts that can happen in the same time.

@PersistenceContext takes care to create a unique EntityManager for every transaction (communication with the database). In a production application you can have multiple clients calling your application in the same time. For each call, the application will create a new thread, will open/create a new transaction with the database and will assign a separate persistence context. Each thread, in this case, must use its own EntityManager.

Conclusion:

Please also check the ACID four key properties of a transaction: atomicity, consistency, isolation, and durability. Conclusion: The PersistenceContext is the context for each transaction and makes those four properties be possible.

Other thread related properties of the EntityManager:

usually the EntityManager or Session are bound to the thread (implemented as a ThreadLocal variable).

Source: https://stackoverflow.com/a/42074452/2623162

EntityManager instances are not thread-safe. 

Source: https://docs.oracle.com/cd/E19798-01/821-1841/bnbqy/index.html

Other info related to the @PersistenceContext

Please notice that @PersistenceContext annotation comes from javax.persistence package, not from spring framework. In JavaEE it is used by the JavaEE container (aka the application server) to inject the EntityManager. Spring borrowed the PersistenceContext annotation to do the same: to inject an application-managed (= not container-managed) EntityManager bean per thread, exactly as the JavaEE container does.

UPDATE:

I updated the answer because it was confusing. Thank you, @silver_mx - his comment bellow

4
  • 1
    I can confirm this when talking about threads. For example, without @PersistenceContext my application runs SQL insert/update in other thread but no changes are made to the database. May 22, 2020 at 7:52
  • 3
    In Spring's context, I do not think this answer is correct. Thread-safety is not an issue according to the documentation (see an answer for this question stackoverflow.com/a/74611778/677096). The difference comes down about how to refer to different entity managers (when using multiple datasources), i.e. @PersistentContext(name = "emBeanName") or @Qualifier("emBeanName")@Autowired. Spring normally injects a proxy that handles threading issues as far as I have seen.
    – silver_mx
    Nov 30, 2023 at 8:02
  • @silver_mx: I updated the answer to check also your comment, thank you
    – Alex
    Mar 1 at 9:55
  • 1
    @silver_mx: I refactored the answer because it was really confusing, thank you very much
    – Alex
    Mar 1 at 10:54
42

@PersistenceContext allows you to specify which persistence unit you want to use. Your project might have multiple data sources connected to different DBs and @PersistenceContext allows you to say which one you want to operate on

check the explanation here: http://www.coderanch.com/t/481448/java-EJB-SCBCD/certification/unitName-PersistenceContext

32

@PersistenceContext:

does not return entity manager instance

it returns container-managed proxy that acquires and releases presistence context on behalf of the application code

18

@PersistenceContext is a JPA standard annotation designed for that specific purpose. Whereas @Autowired is used for any dependency injection in Spring. Using @PersistenceContext gives you greater control over your context as it provides you with ability to specify optional elements e.g. name, properties

2
  • 1
    I know this, but what is the impact in the application? Consider using the standard @Transactional from Spring. When using the @Autowired, the same behaviour as using @PersistenceContext will occur and have the em per application transaction? Jul 10, 2015 at 7:58
  • 5
    I believe it is typically best practice to use @PersistenceContext as it more closely describes the type of dependency injection you are trying to achieve. In addition it provides optional parameters specifically for the use of a EntityManager, this can be useful when you have more than one EntityManager. Functionally I believe you could achieve the same injection with @Autowired, but I would recommened using the annotation designed to be used like this.
    – Alex
    Jul 10, 2015 at 8:15
2

I think @Autowire will work same way as @PersistenceContext

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.misc.jpa-context

When working with multiple EntityManager instances and custom repository implementations, you need to wire the correct EntityManager into the repository implementation class. You can do so by explicitly naming the EntityManager in the @PersistenceContext annotation or, if the EntityManager is @Autowired, by using @Qualifier.

As of Spring Data JPA 1.9, Spring Data JPA includes a class called JpaContext that lets you obtain the EntityManager by managed domain class, assuming it is managed by only one of the EntityManager instances in the application. The following example shows how to use JpaContext in a custom repository:

1

Info from Spring team on how to use @Autowired with Entity manager provided here.

The recommendations are:

For the time being, a plain Spring application can define a bean of type org.springframework.orm.jpa.support.SharedEntityManagerBean, wiring it to a specific EntityManagerFactory, potentially defining a qualifier on it (e.g. the persistence unit name) - and then injecting it via @Autowired and the common qualifier mechanism if necessary, or simply through a plain constructor argument.

Due to the separate nature of the shared EntityManager instance, there is no first-class mechanism to do so implicitly. An explicit SharedEntityManagerBean is a straightforward FactoryBean matched by type and does not require additional post-processors. Alternatively, you could declare an @Bean method which returns an EntityManager built through SharedEntityManagerCreator.createSharedEntityManager, not even involving a FactoryBean then:

@Bean
public EntityManager sharedEntityManager(EntityManagerFactory emf) {
    return SharedEntityManagerCreator.createSharedEntityManager(emf);
}

That's essentially what Spring Data JPA's post-processor ends up registering as well. If there is nothing else we can do at the core Spring Framework level, maybe we should explicitly show the approach above in the reference documentation.

-3

You can create the following FactoryBean to make EntityManager properly injectable, even via constructor injection:

/**
 * Makes the {@link EntityManager} injectable via <i>@Autowired</i>,
 * so it can be injected with constructor injection too.
 * (<i>@PersistenceContext</i> cannot be used for constructor injection.)
 */
public static class EntityManagerInjectionFactory extends AbstractFactoryBean<EntityManager> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Class<?> getObjectType() {
        return EntityManager.class;
    }

    @Override
    protected EntityManager createInstance() {
        return entityManager;
    }

}

Please note, that because we use the @PersistenceContext annotation internally, the returned EntityManager will be a proper thread-safe proxy, as it would have been injected directly at the place of usage with field injection (using @PersistenceContext).

1
  • 1
    If I understand correctly, the entityManager variable in your factory will only be injected once, and your factory probably only has one instance which means every createInstance() calling will return the same EntityManager. So it is a totally useless wrapper.
    – Chenhe
    Oct 9, 2023 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.