我正在评估这种允许实体访问实体管理器的设计。
图书实体:
@Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long isbn;
private String nom;
public void save() {
System.out.println("OWN PERSIST !");
**ThreadLocalEntityManager.em().persist(this);**
}
}
图书服务:
@Stateless
@Interceptors(EntityManagerInjector.class)
public class BookService {
public void create()
{
Book b=new Book(1,2,"3");
b.save();
}
}
EntityManagerInjector
public class EntityManagerInjector implements Serializable {
@PersistenceContext
private EntityManager em;
@AroundInvoke
public Object associate(InvocationContext ic) throws Exception {
ThreadLocalEntityManager.associateWithThread(em); //statically imported method
try {
return ic.proceed();
} finally {
ThreadLocalEntityManager.cleanupThread();
}
}
}
ThreadLocalEntityManager
public class ThreadLocalEntityManager {
private static final ThreadLocal<EntityManager> THREAD_WITH_EM = new ThreadLocal<EntityManager>();
private ThreadLocalEntityManager() {
}
public static void associateWithThread(EntityManager em) {
THREAD_WITH_EM.set(em);
}
public static EntityManager em() {
System.out.println("gettint entitymanger from thread:"+THREAD_WITH_EM.toString());
System.out.println("entitymanger id:"+THREAD_WITH_EM.get().toString());
return THREAD_WITH_EM.get();
}
public static void cleanupThread() {
THREAD_WITH_EM.remove();
}
}
我有一些疑问:
- 这是避免使用 crud 服务(创建、删除、findXX)的好设计吗?
- 这种设计可以在容器中创建任何类型的运行时执行问题吗?
- 将
book.save()
声明更改为静态是简化对“持久性操作”的访问的好方法(避免新的Book().find(id)"
?
谢谢 。ps1:我正在使用JPA 2
,Ejb 3.1
和 Glassfish 3.1.2
ps2:我在 Real World Java EE Patterns Rethinking Best Practices (Adam Bien) 中找到了这个设计