Fabricio Koch
Fabricio Koch

Reputation: 1435

Inject EntityManagerFactory using @PersistenceUnit on Jersey with Wildfly

I'm trying to inject EntityManagerFactory using @PersistenceUnit, but it's always null.

I think my persistence.xml is OK, since I can get the EntityManager with this code:

EntityManager em = Persistence.createEntityManagerFactory("myPersistenceUnit").createEntityManager();

So, I would like to know if I'm doing something wrong, or if this is not possible when using Jersey (2.23) and Wildfly 10 (JBoss EAP 7).

Here is what I've done so far:

Upvotes: 6

Views: 5376

Answers (3)

Fabricio Koch
Fabricio Koch

Reputation: 1435

It seems that Jersey conflicts with Resteasy. This way, I had 2 options:

  • Turn-off Resteasy on JBoss/Wildfly (I know that's possible, but I don't know how);
  • Remove Jersey and use Resteasy instead;

I ended up choosing the 2nd option because it was easier and I have no reasons to use specifically Jersey.

This way, I had to change my web.xml, replacing this:

<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
...
<servlet-mapping>
  <servlet-name>Jersey Web Application</servlet-name>
  <url-pattern>/webapi/*</url-pattern>
</servlet-mapping>

For this:

<servlet-name>javax.ws.rs.core.Application</servlet-name>
...
<servlet-mapping>
  <servlet-name>javax.ws.rs.core.Application</servlet-name>
  <url-pattern>/webapi/*</url-pattern>
</servlet-mapping>

*Another option was to create a class extending Application class.

*beans.xml was not necessary.

Then, I annotated my resource class with @Stateless and I was able to inject EntityManager properly:

@Path("myresource")
@Stateless
public class MyResource {

  @PersistenceContext(unitName="myPersistenceUnit")
  private EntityManager em; 
...

At this point, EntityManager was OK, but somehow it was using JBoss h2 in-memmory database (ExampleDS). So, I configured an oracle datasource on JBoss (OracleDS) and updated my persistence.xml to use OracleDS and JTA instead of "RESOURCE_LOCAL":

<persistence-unit name="myPersistenceUnit" transaction-type="JTA">
  <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
  <jta-data-source>java:jboss/datasources/OracleDS</jta-data-source>
...

With those steps I was able to inject EntityManager and make my CRUD operations successfully.

Upvotes: 4

Gab
Gab

Reputation: 8332

There is no point for a @ManagedBean annotation here, this is a JSF annotation and I according to your code you're trying to expose a REST layer.

Just remove it and all will be fine (also ensure that you have a beans.xml in your classpath to enable CDI, otherwise annotate your class with @Stateless)

Upvotes: 1

Elgayed
Elgayed

Reputation: 1219

I think Entity manager should be enough :

 @PersistenceUnit(unitName= "myPersistenceUnit")
   private EntityManager em;

Upvotes: 0

Related Questions