Jetty Data Source, Hibernate, datasource not found

2019-02-20 16:06发布

问题:

I'm attempting to configure a data source in Jetty 7.4. I was able to do this successfully with my webapp in a Tomcat context.xml.

Here's what I have in the jetty.xml (this is going to be the only application in this jetty instance, so I don't mind having the DB connection server-wide - I'd rather not have to configure it inside the war). It's at the very bottom just above the last </Configure>:

<New class="org.eclipse.jetty.plus.jndi.Resource" id="myDB">
    <Arg>
      <Ref id="Server"/>
    </Arg>
    <Arg>jdbc/myDB</Arg>
    <Arg>
        <New class="com.microsoft.sqlserver.jdbc.SQLServerDataSource">
            <Set name="URL">jdbc:sqlserver://SERVERNAME;databaseName=DATABASENAME;sendStringParametersAsUnicode=false</Set>
            <Set name="user">USERNAME</Set>
            <Set name="password">PASSWORD</Set>
        </New>
    </Arg>
</New>

In my webapp's WEB-INF/web.xml:

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

Finally, in my hibernate.cfg.xml:

<property name="connection.datasource">java:comp/env/jdbc/myDB</property>

Yet, I'm getting a datasource not found error, and I also see the following NameNotFoundException:

javax.naming.NameNotFoundException; remaining name 'env/jdbc/myDB'

When I start up Jetty with debugging enabled, it looks like it's registering the name and everything, although I'm far from being a Jetty expert. Did I miss a step here? What's left?

回答1:

Yep, that's a bizzarerry of some application servers. Some need the "java:comp/env" prependded to the JNDI resource name, some do not. I think Spring has even an option for enabling/disabling that prefix when you declare a JNDI resource bean (like a datasource).

Try:

<property name="connection.datasource">jdbc/myDB</property>

in your Hibernate config.