1

How can I access the EntityManager from an arbitrary bean in Spring Boot? By arbitrary I mean not a service or repository bean. I tried this:

public class CriteriaFinder<T extends IdentityOwner> {
    // THIS DOES NOT WORKS
    @Autowired
    @PersistenceContext
    private EntityManager em;

    public  List<T> find(List<QueryParameter> parameters, Class<T> clazz) {

        if(em == null)
        {
            logger.error("Entity manager is null in finder");
            return null;
        }
        ...
    }
}

I tried with/without @Autowired and @PersistenceContext annotations and with both.

(I want to use the criteria finder with containment to implement custom find)

In a custom @Repository implementation I can access the EntityManager:

public class CustomerRepositoryImpl implements CustomerFinderRepository {
    // THIS WORKS
    @PersistenceContext
    private EntityManager em;
    ...
}

I assume it has something to do with the way Spring is finding and initializing beans. I would also like to avoid passing the EntityManager with a constructor or setter.

Matei Florescu
  • 1,155
  • 11
  • 23

1 Answers1

0

You may inject @PersistenceContext and any Spring bean in general in any class while this class is a Spring bean.
You have some tips to bypass this rule. For example by using ApplicationContextAware but this should be used only in corner cases.

So make CriteriaFinder a Spring bean or pass it to the EntiyManager as parameter in the constructor.
The first way is advised if you want to take advantage of Spring features such as transactions management as you manipulate the EntiyManager instance.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 1
    Right, I realize this now. What throw me off was the same code (with the @PersistentContext annotation) is working for the custom repository. I missed the repository is also created by Spring. – Matei Florescu Nov 06 '17 at 11:47