如何在JBoss AS上使用带有持久性单元的EJB 3?

时间:2016-11-29 23:52:09

标签: jboss ejb persistence.xml persistence-unit

我有一个JBoss AS,在这个服务器上有一个standalone.xml文件,其中有几个属性,也有我的数据源,所以如何将standalone.xml文件中的数据源与我想要的持久性单元结合起来添加到EJB?

1 个答案:

答案 0 :(得分:0)

只需将<jta-data-source>java:/ExampleDS</jta-data-source>添加到persistence.xml即可提供数据源jndi-name。

数据源示例:

<datasource jndi-name="java:/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
                    <driver>h2</driver>
                    <security>
                        <user-name>sa</user-name>
                        <password>sa</password>
                    </security>
                </datasource>

引用数据源的persistence.xml示例ExampleDS:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
   <persistence-unit name="example">
      <jta-data-source>java:/ExampleDS</jta-data-source>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence>

在EJB3中注入持久性单元的示例:

@Stateless
public class MyEJB {

    @PersistenceContext(unitName="example") protected EntityManager entityManager;

    public void createEmployee(String fName, String lName) {
        Employee employee  = new Employee();
        employee.setFirstName(fName);
        employee.setLastName(lName);
        entityManager.persist(employee);
    }
...
}