Obtaining handle to EntityManager in Spring Boot

前端 未结 1 1851
走了就别回头了
走了就别回头了 2021-02-04 03:54

Is there any way to get a handle to the EntityManager for a given entity object? I\'m using spring boot 1.2.3 with JPA starter and i\'m further explicitly configuring multiple d

1条回答
  •  梦如初夏
    2021-02-04 04:10

    It depends how you've been configuring this but have you tried to inject the EntityManager with a qualifier that corresponds to the factory that created it?

    Here is a sample project with two data sources. If you want to inject the EntityManager for order, just do the following in any Spring bean of the project

    @Service
    public class FooService {
    
        private final EntityManager entityManager;
    
        @Autowired
        public FooService(@Qualifier("orderEntityManager") EntityManager entityManager) {
            ...
        }
    
    }
    

    For customer, use the customerEntityManager.

    Of course you can use the persistent unit name instead, that is

    @PersistenceContext(unitName = "customers")
    private EntityManager entityManager;
    
    @PersistenceContext(unitName = "orders")
    private EntityManager entityManager;
    

    Check the configuration of the project for more details.

    0 讨论(0)
提交回复
热议问题