在 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>
我在catalina.out中看到它被绑定了,所以我想这是没问题的。
在我的Web应用程序中,我有指向数据源的链接,我不确定这是否正确:
<Context>
<ResourceLink global='jdbc/myds' name='jdbc/myds' type="javax.sql.Datasource"/>
</Context>
在应用程序中有一个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>
这应该是可以的,但最有可能是这里或者ResourceLink定义错误,因为我收到了以下错误信息:
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
出了什么问题?为什么不起作用?
更新:
我尝试直接获取数据源:
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) { }
}
我的web.xml文件:
<listener>
<display-name>Listener</display-name>
<listener-class>WebAppListener</listener-class>
</listener>
尽管我连接到Tomcat并在JMX控制台中看到数据源(Catalina - Datasource - javax.sql.Datasource = "jdbc/myds":ObjectName = Catalina:type=DataSource,class=javax.sql.DataSource,name="jdbc/myds"),但仍然收到相同的错误。