Cannot call JNDI resource in persistence.xml file

空扰寡人 提交于 2020-01-04 11:44:28

问题


Although it seems many users faced the same problem, I have to post my own issue, taking in account that for now, no suggestion from those already present worked for me. Or maybe am I missing something?

Here is my persistence.xml file (located uner resources/META-INF/ directory, in a maven project):

<?xml version="1.0" encoding="UTF-8"?>
<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="brass-unit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
                <property name="hibernate.connection.datasource" value="java:/comp/env/jdbc/BrassDB"/> 
    </properties>
</persistence-unit>

under resources/META-INF I also have context.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/BrassDB" auth="Container" type="javax.sql.DataSource" 
              driverClassName="org.postgresql.Driver" 
              url="jdbc:postgresql://localhost:5432/mydb" username="usr" password="pwd" 
              maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>

In the web.xml file I have:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>brass_directory_business</display-name>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list> 
<resource-ref>
    <description>db connection</description>
    <res-ref-name>jdbc/BrassDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

Note on web.xml: sometimes I commented resource-ref tag, but the same behavior results.

Now, in my servlet, when I run this, everything works fine:

InitialContext ctx = null;
try {
    ctx = new InitialContext();
    if (ctx == null) {
        throw new Exception("no context!");
    }
    DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/BrassDB");
    if (ds == null) {
        throw new Exception("data source not found!");
    }
    Connection conn = ds.getConnection();
    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM person");
    int n = 0;
    while (rs.next()) {
        n++;
    }
    System.out.println("rs length is: " + n);
} catch (Exception e) {
    e.printStackTrace();
}

But when I run this:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("brass-unit");
EntityManager em = emf.createEntityManager();       
em.createNamedQuery("Person.findAll", Person.class).getResultList();

I get this exception:

Mar 04, 2014 4:48:56 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.banco.Test] in context with path [/brass_directory_business] threw exception
javax.persistence.PersistenceException: Unable to build entity manager factory
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:81)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at com.banco.Test.doPost(Test.java:34)
    at com.banco.Test.doGet(Test.java:27)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [java:/comp/env/jdbc/BrassDB]
    at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:117)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:115)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:399)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:73)
    ... 26 more
Caused by: javax.naming.NameNotFoundException: Name [java:/comp/env/jdbc/BrassDB] is not bound in this Context. Unable to find [java:].
    at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
    at javax.naming.InitialContext.lookup(InitialContext.java:415)
    at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:114)
    ... 42 more

My pom.xml looks like:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    //......
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        //...
    </dependencies>
    <build>
        <plugins>
            <plugin>
        //...
            </plugin>
        </plugins>
    </build>
</project>

I'm using tomcat 7.0.52 as server. Does anyone have any suggestion how to solve my issue?


回答1:


To me, it seems that this issue is a Hibernate problem. I just changed hibernate version to 4.2.7, and it works well.




回答2:


I have another idea:

1.Add <exclude-unlisted-classes>false</exclude-unlisted-classes> to your persistence.xml, <persistence-unit> elemet

2.Add the following to your persistence.xml, <persistence-unit>/<properties> element:

<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:standalone"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>

Besides, try removing the hibernate-core dependency from your pom.xml.

Now you should be able to use the entitymanager. If you need the JDBC connection, just take it from the EntityManager instance (not the way you took it with JNDI).



来源:https://stackoverflow.com/questions/22175544/cannot-call-jndi-resource-in-persistence-xml-file

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