简体   繁体   English

Java EE5 +中的可配置持久性

[英]Configurable persistence in Java EE5+

There are 2 ways of using a persistence unit , code or annotation. 有两种使用持久性单元 ,代码或注释的方法。

CODE
[..] [..]
EntityManagerFactory emf; EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("SOMEPU"); emf = Persistence.createEntityManagerFactory(“ SOMEPU”);
[..] [..]

or 要么

ANNOTATION 注解
[..] [..]
@PersistenceContext(name = "persistence/LogicalName", unitName = "SOMEPU") @PersistenceContext(name =“ persistence / LogicalName”,unitName =“ SOMEPU”)
[..] [..]

Question: If you want to change the persistence unit (or point to different jdbc source), I could easily adapt the sourcecode version to read a variable from some settings file or whatever. 问题:如果要更改持久性单元(或指向不同的jdbc源),我可以轻松地调整源代码版本以从某些设置文件或任何其他文件中读取变量。 But I cant put variables into annotations. 但是我不能将变量放入注释中。 Whats is the solution ? 有什么解决方案?

Yes, I could keep always the same PU and just point the jbdc resource in the applicationserver to somewhere else, but I dont want anyone to tinker around in the admin settings of the AS. 是的,我可以始终保持相同的PU,只是将applicationserver中的jbdc资源指向其他位置,但是我不希望任何人修改AS的管理设置。

cheers Sven 欢呼斯文

If you absolutely have to use annotations to get your PersistenceContext, then I guess you could wrap the creation of the EntityManager in some class and then have that injected into the bean that requires it? 如果您绝对必须使用批注来获取PersistenceContext,那么我想您可以将EntityManager的创建包装在某个类中,然后将其注入到需要它的bean中?

public interface MyPersistenceContext
{
      public void getEntityManager();
}

And then in your EJB: 然后在您的EJB中:

public class MyEJB
{

      @EJB
      private MyPersistenceContext persistenceContext;

      private EntityManager em;

      @PostConstruct
      public void postConstruct()
      {
             em = persistenceContext.getEntityManager();
      }

 ....

How the implementation of MyPersistenceContext you provide creates the EntityManager is up to you. 您提供的MyPersistenceContext的实现如何创建EntityManager取决于您。

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

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