Injecting EntityManager in JBoss/WildFly

2019-05-06 06:21发布

问题:

I am learning JPA, EJB and JBoss/WildFly.

I need to inject an EntityManager into my application. I am trying to do it in the following way:

@Stateless
@LocalBean
public class ProductsService implements IProductsService {

    @PersistenceContext(unitName = "myUnit")
    EntityManager entityManager;

//....
}

And I have persistence.xml file in the META-INF directory in my .war archive:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="myUnit">
        <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source> 
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create" />
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

The JNDI data source (java:jboss/datasources/ExampleDS) is the default data source that is provided in a clean WildFly installation.

When I deploy my application to WildFly I get the following error:

JBAS011440: Can't find a persistence unit named myUnit in deployment "my-web-app.war".

What am I doing wrong?

回答1:

persistence.xml always resides in {root-of-persistence-unit}/META-INF/ directory. In a war file you must place the persistence.xml in WEB-INF/classes/META-INF.

Eg:

WEB-INF/classes/META-INF/persistence.xml
WEB-INF/web.xml

See more: Persistence Units