实体经理最佳做法 [英] Entity manager best practices
本文介绍了实体经理最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道哪种方式最适合定义实体经理。我使用的是spring boot
$ b $ case 1)在Spring服务类中创建如下所示的
@Service
@Transactional
public class DemoService {
private static final Logger log = LoggerFactory.getLogger(DemoService.class);
私人EntityManagerFactory emf;
public void getEntity(){
final EntityManager em = emf.createEntityManager();
@PersistenceUnit
public void setEntityManagerFactory(final EntityManagerFactory emf){
this.emf = emf;
}
}
案例2)定义全局实体经理和分享跨所有服务。
注意:每个服务只反映一个单一的实体定义。
解决方案
注入EntityManager是最简单也是最有效的方式:
@PersistenceContext(unitName =persistenceUnit)
private EntityManager entityManager;
- 您不需要设置
EntityManagerFactory
,因为您需要一个事务绑定EntityManager
。 - 您不需要保存
EntityManager
,因为这将是另一个间接层,您可以简单地模拟EntityManager
。 / li>
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.
解决方案
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-boundEntityManager
. - 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 theEntityManager
anyway.
这篇关于实体经理最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文