hainp
hainp

Reputation: 11

How can I use Java console app and Hibernate using Tomcat Context?

I have some Java-console-apps. which are using Hibernate to take care some database stuff (I use MySQL). Now, I want Hibernate to use datasource from Tomcat Context. Could anyone tell me how?

Upvotes: 1

Views: 607

Answers (1)

Aba Dov
Aba Dov

Reputation: 962

Tomcat wiki contains the needed configuration.

in context.xml:

<?xml version="1.0" encoding="UTF-8"?> <Context antiJARLocking="true" path="/DVDStore">
  <Resource auth="Container"
  driverClassName="com.mysql.jdbc.Driver" maxActive="30" maxIdle="10" maxWait="10000" name="jdbc/sakila" password="*****"
  type="javax.sql.DataSource" url="jdbc:mysql://localhost/sakila" username="*****"/>
</Context>

In WEB-INF/web.xml .

<resource-ref>
  <description>This is a MySQL database connection</description>
  <res-ref-name>jdbc/sakila</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

In hibernate.cfg.xml:

<!-- using container-managed JNDI -->
<propertyname="hibernate.connection.datasource">
   java:comp/env/jdbc/sakila
</property>

You can find more in The TomcatHibernate Wiki


Edit:

In case you want to access the context directly, this is the way to do it problematically

    ServletContext sc = getServletContext();  
    String parameterValue = sc.getInitParameter("parameterName");

Upvotes: 1

Related Questions