Java 在persistence.xml 中引用Tomcat JNDI 数据源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2911439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:23:58  来源:igfitidea点击:

referring Tomcat JNDI datasource in persistence.xml

javahibernatetomcatjpadatasource

提问by Rostislav Matl

in server.xml I've defined global resource (I'm using Tomcat 6):

在 server.xml 中我定义了全局资源(我使用的是Tomcat 6):

<GlobalNamingResources>
   <Resource name="jdbc/myds" auth="Container"
             type="javax.sql.DataSource"
             maxActive="10" maxIdle="3" maxWait="10000"
             username="sa"  password=""
             driverClassName="org.h2.Driver"
             url="jdbc:h2:~/.myds/data/db"
   />
</GlobalNamingResources>

I see in catalina.out that this is bound, so I suppose it's OK.

我在 catalina.out 中看到这是绑定的,所以我想这没问题。

In my web app I have the link to the datasource, I'm not sure it's OK:

在我的网络应用程序中,我有指向数据源的链接,但我不确定它是否正确:

<Context>    
 <ResourceLink global='jdbc/myds' name='jdbc/myds' type="javax.sql.Datasource"/>    
</Context>

and in application there is persistence.xml:

在应用程序中有persistence.xml:

<persistence 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"
             version="2.0">
  <persistence-unit name="oam" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <non-jta-data-source>jdbc/myds</non-jta-data-source>
    <!-- class definitions here, nothing else -->

    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
    </properties>
  </persistence-unit>
</persistence>

It should be OK, but most probably this or the ResourceLink definition is wrong because I'm getting:

应该没问题,但很可能这个或 ResourceLink 定义是错误的,因为我得到:

javax.naming.NameNotFoundException: Name jdbc is not bound in this Context

javax.naming.NameNotFoundException:名称 jdbc 在此上下文中未绑定

What's wrong and why this does not work?

出了什么问题,为什么这不起作用?

UPDATE:

更新:

I've tried to get the datasource directly:

我试图直接获取数据源:

public class WebAppListener implements ServletContextListener
{
    // ServletContextListener interface - start
    public void contextInitialized(ServletContextEvent sce)
    {
        try
        {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource)
            envCtx.lookup("jdbc/myds");
        }
        catch (NamingException ex)
        {
            System.out.println("!!!! Got NamingException:");
            ex.printStackTrace(System.out);
        }
    }

    public void contextDestroyed(ServletContextEvent sce) { }

}

my web.xml:

我的 web.xml:

  <listener>
    <display-name>Listener</display-name>
    <listener-class>WebAppListener</listener-class>
  </listener>

Still getting the same error although I see the datasource in JMX console when I connect to the Tomcat (Catalina - Datasource - javax.sql.Datasource = "jdbc/myds" : ObjectName = Catalina:type=DataSource,class=javax.sql.DataSource,name="jdbc/myds". )

尽管我在连接到 Tomcat 时在 JMX 控制台中看到数据源(Catalina - Datasource - javax.sql.Datasource = "jdbc/myds" : ObjectName = Catalina:type=DataSource,class=javax.sql.数据源,名称=“jdbc/myds”。)

回答by JoseK

The <non-jta-data-source>in persistence.xmlshould be

<non-jta-data-source>persistence.xml

java:comp/env/jdbc/myds

java:comp/env/jdbc/myds

as per the response in http://forums.oracle.com/forums/thread.jspa?messageID=1899677

根据http://forums.oracle.com/forums/thread.jspa?messageID=1899677 中的响应

And also is your db driver in $CATALINA_HOME/lib

还有你的数据库驱动程序 $CATALINA_HOME/lib

回答by Pascal Thivent

Did you make that resource available for the application by declaring it in your web.xml?

您是否通过在您的web.xml?

<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/myds</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

回答by Whome

(Im using Apache OpenJPA library in Tomcat7 so may not match to Hibernate stuff)

(我在 Tomcat7 中使用 Apache OpenJPA 库,所以可能与 Hibernate 的东西不匹配)

I have never used a global jdbc for my OpenJPA webapps but gave it a try. It worked and this is my configuration. See folder where persistence.xml is saved, probably is openjpa problem but without it nothing works.

我从未在我的 OpenJPA 网络应用程序中使用过全局 jdbc,但尝试了一下。它有效,这是我的配置。查看保存persistence.xml 的文件夹,可能是openjpa 问题,但没有它就没有任何作用。

myapp/WEB-INF/classes/META-INF/persistence.xml
this is using openjpa provider so class list may not be needed in hibernate.

myapp/WEB-INF/classes/META-INF/persistence.xml
这是使用 openjpa 提供程序,因此在休眠中可能不需要类列表。

<?xml version="1.0" encoding="UTF-8"?> 
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<persistence-unit name="main" transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <non-jta-data-source>java:comp/env/jdbc/mydb</non-jta-data-source>

    <class>com.myapp.db.User</class>
    <class>com.myapp.db.Server</class>

    <properties>
        <property name="openjpa.DynamicEnhancementAgent" value="false" />
        <property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" /> 
        <property name="openjpa.Log" value="commons" />
        <property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
    </properties>
</persistence-unit>

</persistence>

tomcat/conf/server.xml
Add global jdbc resource.

tomcat/conf/server.xml
添加全局 jdbc 资源。

  ..cut...
  <GlobalNamingResources>
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" readonly="true"  />

    <Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="20" maxWait="10000"
        username="myuser" password="mypwd"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=utf8"
        validationQuery="SELECT 1" removeAbandoned="true" removeAbandonedTimeout="300"
    />
  </GlobalNamingResources>
  ..cut...

tomcat/conf/Catalina/localhost/myapp.xml
this my development box so I use docBase to link directly to projects folder. You should be find inserting this to war package (META-INF/context.xml) when deployed to production box.

tomcat/conf/Catalina/localhost/myapp.xml
这是我的开发框,所以我使用 docBase 直接链接到项目文件夹。部署到生产框时,您应该会发现将其插入到 war 包 (META-INF/context.xml) 中。

<?xml version="1.0" encoding="UTF-8"?>
<Context docBase="/projects/myapp/web" reloadable="true" crossContext="true" >

  <Realm className="org.apache.catalina.realm.DataSourceRealm"
    dataSourceName="jdbc/mydb" localDataSource="false" digest="SHA"
    userTable="user"            userNameCol="username" userCredCol="password"
    userRoleTable="user_role_v" roleNameCol="role" 
  />

  <ResourceLink name="jdbc/mydb" global="jdbc/mydb" type="javax.sql.DataSource" />
</Context>

myapp/WEB-INF/web.xml
Add resource-ref to the end of file.

myapp/WEB-INF/web.xml
将 resource-ref 添加到文件末尾。

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0" >

  <description>Webapp</description>
  <display-name>Webapp</display-name>
  ..cut...

  <resource-ref>
    <description>mydb</description>
    <res-ref-name>jdbc/mydb</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

</web-app>

Because Im using OpenJPA+Tomcat7 (not fullsized j2ee container) this may look overengineering but thats how it works. Results are good and developing db-aware webapps is very easy. No need to manual sql query hardcoding and oldskool DAO classes.

因为我使用的是 OpenJPA+Tomcat7(不是全尺寸的 j2ee 容器),这可能看起来过度设计,但这就是它的工作原理。结果很好,开发 db-aware webapps 非常容易。无需手动 sql 查询硬编码和 oldskool DAO 类。