5

这是我的 SLSB:

@Stateless
public class MyService {
  PersistenceContext(unitName = "abc")
  EntityManager em;
  public boolean exists(int id) {
    return this.em.find(Employee.class, id) != null;
  }
}

这是我的persistence.xml(我使用的是 Glassfish v3):

<persistence>
  <persistence-unit name="abc">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/MyDS</jta-data-source>
    <properties>
        <property name="hibernate.archive.autodetection" value="class" />
        <property name="hibernate.dialect"
          value="org.hibernate.dialect.MySQLInnoDBDialect" />
    </properties>
  </persistence-unit>
</persistence>

现在我正在尝试使用 OpenEJB 嵌入式容器创建一个测试。这是我的测试课:

class MyServiceText {
  @Test
  public void testChecksExistence() throws Exception {
    Properties properties = new Properties();
    properties.setProperty(
        javax.naming.Context.INITIAL_CONTEXT_FACTORY,
        "org.apache.openejb.client.LocalInitialContextFactory"
    );
    InitialContext ic = new InitialContext(properties);
    // actual testing skipped
  }
}

我想使用 HSQL 进行测试。如何指示 OpenEJB"abc"在测试期间我的持久性单元必须指向 HSQL?我要创建一个新版本persistence.xml吗?我要使用openejb.xml吗?我迷失在他们的示例和文档中.. :(

这是一个 Maven-3 项目。

4

1 回答 1

6

我建议为您的 OpenEJB 配置放置一个名为jndi.propertiesin的文件。src/test/resources这将在测试类路径中可用,然后您可以使用 InitialContext 的无参数构造函数来查找数据源和 ejb。示例配置如下所示,我使用 mysql 作为我的数据源:

java.naming.factory.initial=org.apache.openejb.client.LocalInitialContextFactory

myDS=new://Resource?type=DataSource
myDS.JdbcDriver=com.mysql.jdbc.Driver
myDS.JdbcUrl=jdbc:mysql://127.0.0.1:3306/test
myDS.JtaManaged=true
myDS.DefaultAutoCommit=false
myDS.UserName=root
myDS.Password=root

然后 OpenEJB 应该自动用这个数据源替换 persistence.xml 中的引用,如果这是唯一的数据源,那么即使名称不同,它也应该可以工作。

编辑:持久性单位设置

根据您引用的文档,还应该可以通过 jndi.properties 配置持久性单元属性:

abc.hibernate.hbm2ddl.auto=update
abc.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect

我自己没有测试过这个,因为我使用 mysql 进行测试和正常执行,只有不同的数据库名称。请让我知道这是否可行,我也一直在考虑在我的测试用例中替换 mysql 。

于 2010-10-28T13:52:44.860 回答