Entity manager best practices

↘锁芯ラ 提交于 2020-01-15 12:09:28

问题


I would like to know which way is the best to define entity manager. I am using spring boot

case 1) creating in spring service class like follows

@Service
@Transactional
public class DemoService {

    private static final Logger log = LoggerFactory.getLogger(DemoService.class);

    private EntityManagerFactory emf;

    public void getEntity(){
        final EntityManager em = emf.createEntityManager();
    }

    @PersistenceUnit
    public void setEntityManagerFactory(final EntityManagerFactory emf) {
        this.emf = emf;
    }

}

Case 2.) Define a global entity manager and share it across all services.

Note : Each service only reflects one single Entity definition.


回答1:


Injecting the EntityManager is the simplest and the most effective way to do it:

@PersistenceContext(unitName = "persistenceUnit")
private EntityManager entityManager;
  • You don't need to set the EntityManagerFactory, since you need a transaction-bound EntityManager.
  • You don't need to hold the EntityManager in a global component, since that would be yet another indirection layer and you can simply mock the EntityManager anyway.


来源:https://stackoverflow.com/questions/30621885/entity-manager-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!