我使用 MySQL 数据库和 Hibernate 在 Netbeans 6.5 中开发了一个 Java Web 应用程序。开发数据库服务器和开发应用程序服务器 (Tomcat 6) 都驻留在我的开发机器上。一切正常;应用程序正确地从数据库中提取数据。
现在,我已准备好将其移至生产服务器。同样,数据库服务器和应用程序服务器在同一台机器上。我部署 WAR 文件并尝试访问该应用程序;我可以访问静态页面,但使用数据库的 Servlet 出现异常:
org.hibernate.exception.JDBCConnectionException: 无法打开连接
我很确定问题与 Tomcat 不知道数据源有关。似乎 Netbeans 为我处理了这个问题。我读到我可能需要添加一个 RESOURCE 条目,所以我从 this site 那里得到了一些建议这给了我一个 context.xml 的:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/EmployeeDirectory">
<Resource
name="jdbc/employeedirectory" auth="Container"
type="javax.sql.DataSource" username="EmployeeDir"
password="EmployeeDirectory" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/EmployeeDirectory?autoReconnect=true"
maxActive="15" maxIdle="7"
validationQuery="Select 1" />
</Context>
一个 web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<!-- Omit Servlet Info -->
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/employeedirectory</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
和一个 hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.datasource">java:comp/env/jdbc/employeedirectory</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Omit other Mappings -->
<mapping class="EmployeeDirectory.data.PhoneNumber" resource="EmployeeDirectory/data/PhoneNumber.hbm.xml"/>
</session-factory>
</hibernate-configuration>
现在,我得到了一个 org.hibernate.HibernateException: Could not find datasource
错误。
我是否走在从开发到生产的正确道路上?我错过了什么?
最佳答案
我认为您走在正确的轨道上。我会首先设置数据源并在 hibernate 之外验证它。这是一篇很好的文章:http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.htm以及此处的一些示例:http://www.mbaworld.com/docs/jndi-datasource-examples-howto.html
然后,我将配置 hibernate 以使用数据源。通过查看您的 hibernate.cfg.xml
文件,我认为您应该尝试将 hibernate.connection.datasource
更改为 jdbc/employeedirectory
关于database - 从 Netbeans Dev 到 Tomcat Production : DB Connection Not Found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/855918/