繁体   English   中英

在 TomEE 中使用来自 context.xml 的 JDBC 数据源

[英]Using JDBC datasources from context.xml in TomEE

TomEE 是一个很棒的项目,它结合了 Tomcat 的轻量级体验和 Java EE 的特性。 我在 context.xml 中声明了许多 JDBC 数据源,但是当我想通过 JNDI 使用该数据源时,我得到一个异常。 那么我如何才能在 TomEE 的 context.xml 中声明一个 JDBC 数据源

我在 context.xml 中声明的数据源

 <Resource auth="Container" 
        name="local_jdbc_db"  
        type="javax.sql.DataSource" 
        driverClassName="com.mysql.jdbc.Driver"  
        url="jdbc:mysql://localhost:3306/mydb" 
        username="user" 
        password="pass"      /> 

从 JNDI 获取数据源的代码

Context contextoInicial = new InitialContext();
Context contexto = (Context) contextoInicial.lookup("java:comp/env");
DataSource ds= (DataSource) contexto.lookup("local_jdbc_db");

更新 致所有在使用 TomEE 时遇到这种罕见问题的人:我尝试在 context.xml 中创建数据源并在 TomEE JAX-RS 1.5.0 版中部署,但没有成功,它总是向我抛出空指针异常并且找不到数据源名称。 最近我在 TomEE JAX-RS 1.6.0 版中尝试了同样的方法:我在 context.xml 中创建了我的数据源并使用此代码创建了一个简单的 servlet

     Context initContext = new InitialContext();
     Context envContext = (Context) initContext.lookup("java:/comp/env");
     DataSource dataSource = (DataSource) envContext.lookup("jdbc_northwind");
     try (Connection conn = dataSource.getConnection(); 
           Statement s = conn.createStatement();
           ResultSet rs = s.executeQuery("select * from customers")) {
           while (rs.next()) {
                out.print(rs.getString("CompanyName"));
                out.print("<br>");
           }         
       } 

...启动服务器和万岁!!!! 它显示了我的结果!,但我有点失望,因为当我重新部署应用程序时,它向我显示了旧的异常(未找到数据源,空指针异常)所以我尝试了最后一件事:在 web.xml 中注册数据源

  <resource-ref>
        <res-ref-name>jdbc_northwind</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref> 

并重新启动服务器和...它工作,重新部署应用程序并且工作得很好!,但这种行为很奇怪:在Tomcat中,我从未在web.xml中声明我的数据源,并且数据源没有问题。 也许是一个错误?

更新:已确认是一个错误,似乎将在 TomEE 1.6.1 中解决 更新 2:已在 TomEE 1.7.0 中解决

你看过文档吗? http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html此外,您能否提供您收到的异常?

因为我在这个问题上花了很多时间,我终于在阅读该主题的手册 (RTFM) 的 15 分钟内找到了答案: http : //tomee.apache.org/configuring-datasources.html

tomee.xml 中数据库资源的正确 JNDI 命名空间是:“java:openejb/Resource/...”

只是留在这里以防万一其他人来寻找这个问题。

当我可以阅读手册时,我无法强调我浪费了多少时间。 哦,好吧:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM