问题
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-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.
来源:https://stackoverflow.com/questions/30621885/entity-manager-best-practices