How to access Spring Data configured entity manager (factory) in custom implementation

后端 未结 3 866
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 22:57

I\'m writing a custom implementation for a Spring Data JPA repository. So I have:

  • MyEntityRepositoryCustom => interface with the custom methods
3条回答
  •  隐瞒了意图╮
    2020-12-23 23:40

    Since version Spring Data JPA 1.9.2 you have access to EntityManager through JpaContext, see: http://docs.spring.io/spring-data/jpa/docs/1.9.2.RELEASE/reference/html/#jpa.misc.jpa-context. Example:

    @Component
    public class RepositoryUtil
    {
        @Autowired
        private JpaContext jpaContext;
    
        public void deatach(T entity)
        {
            jpaContext.getEntityManagerByManagedType(entity.getClass()).detach(entity);
        }
    }
    

    P.S. This approach will not work if you have more than one EntityManager candidate for some Class, see implementation of JpaContext#getEntityManagerByManagedType -> DefaultJpaContext#getEntityManagerByManagedType.

提交回复
热议问题