mobile_beginner_2015
mobile_beginner_2015

Reputation: 21

How to use EJB 3 with persistence unit on a JBoss AS?

I have a JBoss AS, and on this server there is a standalone.xml file where there several properties, there are my datasources too, so how combine the datasources in the standalone.xml file with a persistence unit that I want to add to an EJB ?

Upvotes: 0

Views: 422

Answers (1)

Elvis Rocha
Elvis Rocha

Reputation: 104

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);
    }
...
}

Upvotes: 0

Related Questions