0

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

4

1 回答 1

0

Just add <jta-data-source>java:/ExampleDS</jta-data-source> providing your datasource jndi-name to the persistence.xml.

Example of Datasource:

<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>

Example of persistence.xml referencing datasource 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>

Example injecting Persistence Unit in your 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);
    }
...
}
于 2016-11-30T01:42:55.467 回答