我正在使用 Tomcat7、Struts-2.3.5、hibernate-4.1.7 和 jotm-2.1.9 width microsoft sqlserver 2005 作为我的 java web 应用程序框架。当我在休眠配置中使用 jndi 数据源时,它拒绝工作。我在这个网站上读过一篇看似的帖子,Configure hibernate to connect to database via JNDI Datasource,并没有解决问题。1、我把资源定义放在tomcat server.xml中,而不是META-INF下的context.xml中;
<Context docBase="C:\workspace\javaspaces\sitexa\web"
privileged="true" antiResourceLocking="false" antiJARLocking="false">
<Resource name="jdbc/sitexaDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="10000"
factory="org.objectweb.jotm.datasource.DataSourceFactory"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://127.0.0.1:1433;databaseName=sitexa"
username="sa" password=""/>
<Resource name="UserTransaction" auth="Container" type="javax.transaction.UserTransaction" />
</Context>
2、我把所有需要数据库连接和jta的lib都放在tomcat文件夹/lib下;
3、在web.xml中:
<resource-env-ref>
<description>DB Connection</description>
<resource-env-ref-name>jdbc/sitexaDB</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>
4、在hibernate.cfg.xml中:
<session-factory>
<property name="hibernate.connection.datasource">java:comp/env/jdbc/sitexaDB</property>
<property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.max_fetch_depth">3</property>
<property name="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.JOTMJtaPlatform</property>
<property name="hibernate.transaction.factory_class">org.hibernate.engine.transaction.internal.jta.JtaTransactionFactory</property>
<property name="hibernate.current_session_context_class">jta</property>
...
</session-factory>
5、异常:
%%%% Error Creating SessionFactory %%%%
org.hibernate.service.jndi.JndiException: Unable to lookup JNDI name [java:comp/env/jdbc/sitexaDB]
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
...
Caused by: javax.naming.NamingException: This context must be accessed through a java: URL
at org.apache.naming.SelectorContext.parseName(SelectorContext.java:776)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:135)
at javax.naming.InitialContext.lookup(InitialContext.java:415)
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)