【问题标题】:Set datasource to JPA without a container在没有容器的情况下将数据源设置为 JPA
【发布时间】:2013-12-27 21:25:11
【问题描述】:

我想用一段时间来测试我的实体一个特殊的数据源

https://code.google.com/p/datasource-proxy/

包装了原始数据源(在我的例子中是 apache derby 的)ClientDataSource

那么如何在没有容器的情况下将数据源注入到我的 JPA 中...?

我尝试使用 simple-jndi 但不起作用。 (不使用 JPA2 的 eclipse 链接实现)

在配置持久化单元时,有没有办法绕过数据源的 JNDI?

(以编程方式?)

谢谢。

【问题讨论】:

    标签: java eclipselink jndi jpa-2.1


    【解决方案1】:

    我找到了 EclipseLink JPA 实现的方法

    import org.eclipse.persistence.config.PersistenceUnitProperties;
    //define your datasource before proxyDS - not shown here
    //then add this property to entity manager factory prop map
    
    emfProps.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, proxyDS);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("CompanyPU", emfProps);
    EntityManager em = emf.createEntityManager();
    

    我仍然想为任何 JPA 提供者找到更通用的方法

    【讨论】:

      【解决方案2】:

      如果您想通过程序设置数据源而不使用容器或JNDI查找,那么您可以使用包含Apache Derby的ClientDataSource的以下方式:

      public DataSource createDataSource() {
         ClientDataSource dataSource = new ClientDataSource();
         dataSource.setServerName("localhost");
         dataSource.setPortNumber(1527);
         dataSource.setDatabaseName("mytestdb");
         dataSource.setUser("myusername");
         dataSource.setPassword("mypasswd");
         return dataSource;
      }
      

      然后你可以把这段代码放在你的应用程序中获取JDBC连接:

      Connection connection = dataSource.getConnection("myusername", "mypasswd");
      

      【讨论】:

      • 我知道该怎么做谢谢......问题是我如何将此数据源附加到完成 jndi 查找的持久性上下文。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 2014-01-07
      相关资源
      最近更新 更多