EntityManagerFactory not being injected using @PersistenceUnit

送分小仙女□ 提交于 2019-12-24 16:25:02

问题


I'm a java beginner. I'm in trouble to configure a persistance unit using JTA transactions. I need to use a PostgreSQL database that is already defined, configured and populated. Using netbeans, i created the persistance.xml and glassfish-resources.xml as fallows:

<persistence version="2.0" 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">
    <persistence-unit name="WellWatcherPU" transaction-type="JTA">
         <jta-data-source>WellWatcherDB</jta-data-source>
         <exclude-unlisted-classes>false</exclude-unlisted-classes>
         <properties>
             <property name="eclipselink.logging.logger" value="org.eclipse.persistence.logging.DefaultSessionLog"/>
             <property name="eclipselink.logging.level" value="FINE"/>
         </properties>
     </persistence-unit>
</persistence>

and

<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_geowellex_geowellexPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="5432"/>
        <property name="databaseName" value="DBNAME"/>
        <property name="User" value="USER"/>
        <property name="Password" value="PASSWORD"/>
        <property name="URL" value="jdbc:postgresql://localhost:5432/DBNAME"/>
        <property name="driverClass" value="org.postgresql.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="WellWatcherDB" object-type="user" pool-name="post-gre-sql_geowellex_geowellexPool"/>
</resources>

And this is how i get the EntityManagerFactory and EntityManager (as used in the netBeans example)

public class EUserDao {

@Resource
private UserTransaction utx = null;
@PersistenceUnit(unitName = "WellWatcherPU")
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
    return emf.createEntityManager();  <-------- NullPointerException here
}

public EUser getOne(long userId){
    EntityManager em = getEntityManager();
    try {
        return em.find(EUser.class, userId);
    } finally {
        em.close();
    }
}

EDIT:

And here is my glassfish deploy log:

Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(1901223982)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--connecting(DatabaseLogin( platform=>DatabasePlatform user name=> "" connector=>JNDIConnector datasource name=>null ))

Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(1462281761)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--Connected: jdbc:postgresql://localhost:5432/geowellex?loginTimeout=0&prepareThreshold=0 User: geowellex Database: PostgreSQL Version: 9.1.3 Driver: PostgreSQL Native Driver Version: PostgreSQL 8.3 JDBC3 with SSL (build 603)

Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(766700859)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--connecting(DatabaseLogin( platform=>PostgreSQLPlatform user name=> "" connector=>JNDIConnector datasource name=>null ))

What's wrong?


回答1:


Most likely problem is that your EUserDao is just regular class. Injection works only for container managed classes. Annotations like @PersistenceUnit and @Resource are not processed for normal classes.

Following types of classes are container managed classes (and in those @PersistenceUnit can be used):

  • Servlet: servlets, servlet filters, event listeners
  • JSP: tag handlers, tag library event listeners
  • JSF: scoped managed beans
  • JAX-WS: service endpoints, handlers
  • EJB: beans, interceptors
  • Managed Beans: managed beans
  • CDI: CDI-style managed beans, decorators
  • Java EE Platform: main class (static), login callback handler



回答2:


I see that in your code declare:

private EntityManagerFactory emf = null;

but never create one... like this

emf = Persistence.createEntityManagerFactory("WellWatcherPU");

Thats why you get a Null Pointer Exception when use the object!

public EntityManager getEntityManager() {
    return emf.createEntityManager();  <-------- NullPointerException here
}


来源:https://stackoverflow.com/questions/10536483/entitymanagerfactory-not-being-injected-using-persistenceunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!