Search code examples
javajpajboss

JBoss 7.1 Datasource JDBC 4.1 Java Persistence-Context


I have a EJB-Project and a JBoss 7.1 Server and a PostgreSQL database. I want to get a Entitymanager by PersistenceContext like this:

@PersistenceContext(name="PlayerService",unitName="PlayerService")
private EntityManager em;

persistence.xml:

<persistence-unit name="PlayerService" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
  <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
...

I start the JBoss Server, go into the admin console and configure a JDBC Datasource. I copied postgresql-9.3-1101.jdbc41.jar into the deployment-Folder of the Server, so I can choose that driver when I create the datasource. The datasource name is PlayerService, the JNDI path is java:jboss/PlayerService. I enabled the datasource also as default Datasource in the JPA Subsystem.

em.getTransaction().begin();

still throws a null pointer, I guess because I try to access the PersistenceContext from outside the server (from a java-class with a seperate main-function for testing). What do I have to do to get that working. Would it work from the deployed project on the server? I have the feeling I'm missing some last step/s.


Solution

  • I try to access the PersistenceContext from outside the server

    In your Unit tests you need to initialize the EntityManager yourself.

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("PlayerService");
    EntityManager em = factory.createEntityManager();