简体   繁体   English

EntityManager初始化最佳实践

[英]EntityManager initialization best practices

When using EntityManager , is it better to get one instance with PersistenceContext and pass it around in my program, or should I use dependency injection more than once? 使用EntityManager ,最好是使用PersistenceContext获取一个实例并在我的程序中传递它,还是应该多次使用依赖注入?

In my application each client will communicate with a stateful session bean, and each bean needs to use EntityManager at some point. 在我的应用程序中,每个客户端将与有状态会话bean通信,并且每个bean需要在某个时刻使用EntityManager I guess that bean methods are invocated concurrently (but I'm not even sure). 我想同时调用bean方法(但我甚至不确定)。 How do I guarantee that I use EntityManager in a thread-safe manner? 我如何保证以线程安全的方式使用EntityManager With transactions? 有交易吗? With a separate instance in each bean? 每个bean中都有一个单独的实例?

Sorry if this is confusing, I'm new to EJB/JPA and I couldn't find any material which addresses my questions. 很抱歉,如果这令人困惑,我是EJB / JPA的新手,我找不到任何解决我问题的材料。

Use @PersistenceContext to inject your EntityManager in your DAO class(es). 使用@PersistenceContext将您的EntityManager注入您的DAO类。 These are the classes that will handle the database operations. 这些是将处理数据库操作的类。 Then in all other (service) classes inject your DAO class(es). 然后在所有其他(服务)类中注入您的DAO类。 Your DAO should be a stateless bean (no need of a remote interface, only local) 你的DAO应该是一个无状态bean(不需要远程接口,只需要本地)

Yes, you should inject the EntityManager instances (which will be different for each thread/client request) into your stateful session beans (which are not invoked concurrently, at least not from different clients). 是的,您应该将EntityManager实例(每个线程/客户端请求将不同)注入有状态会话bean(不会同时调用,至少不会从不同的客户端调用)。

There is no point in creating DAO classes, though. 但是,创建DAO类没有意义。 JPA already is a high-level persistence API that gives you RDBMS independence and portability between different JPA implementations. JPA已经是一个高级持久性API,它为您提供不同JPA实现之间的RDBMS独立性和可移植性。 So, DAOs would only add clutter to the codebase. 因此,DAO只会增加代码库的混乱。

For transactions, you don't really need to do anything. 对于交易,您实际上不需要做任何事情。 Business methods in session beans have a "Required" transaction attribute by default, so they will always run inside a client-specific transaction. 会话bean中的业务方法默认具有“必需”事务属性,因此它们将始终在特定于客户端的事务中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM