-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 12 posts ] 
Author Message
 Post subject: Using Tomcat and JNDI with Hibernate
PostPosted: Tue Jul 11, 2006 11:30 am 
Newbie

Joined: Tue Jul 11, 2006 11:15 am
Posts: 2
Has anyone successfully used Hibernate with Tomcat and JNDI? In particular, I am trying to use the Jakarta Commons DBCP with Tomcat and to have Tomcat pass the datasource and session registered via JNDI to Hibernate for usage. There are some articles that explain this but a comprehensive article and an example would greatly help. Thanks.

- Asad


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 12, 2006 11:25 am 
Beginner
Beginner

Joined: Wed Jun 21, 2006 10:08 am
Posts: 26
Yes, (but with C3P0). For Tomcat 5.5

It's essentially the same except for you use a different class when loading.

So you need to edit 3 files:

1) your Hibernate Config file
Should have only these DB conn settings:
Code:
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.datasource">java:comp/env/jdbc/dataSource</property>


2) create/edit your /META-INF/context.xml
To contain a resource: and change the type="" to your DBCP DataSource
Code:
<Context>

   <Resource auth="Container" description="DB Connection"
      driverClass="oracle.jdbc.OracleDriver" maxPoolSize="4" minPoolSize="2"
      acquireIncrement="1" name="jdbc/websdev" user="userName"
      password="Password"
      factory="org.apache.naming.factory.BeanFactory"
      type="com.mchange.v2.c3p0.ComboPooledDataSource"
      jdbcUrl="yourURL" />

</Context>


Then edit your web.xml to have a reference to this resource:
Code:
   <resource-ref>
      <res-ref-name>jdbc/dataSource</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
   </resource-ref>


Then just do your normal DataSource ds = InitialContext.lookup("java:comp/env/jdbc/dataSource")

_________________
- Jonathan


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 4:23 pm 
Beginner
Beginner

Joined: Tue Sep 27, 2005 2:51 pm
Posts: 27
huangjd wrote:
Yes, (but with C3P0). For Tomcat 5.5


Then just do your normal DataSource ds = InitialContext.lookup("java:comp/env/jdbc/dataSource")


but why would you get a DataSource object? There doesn't seem to be a way (that I've found yet) to push the retrieved ds or a connection requested from it into Hibernate...

What is the next step you do after getting your DataSource?

_________________
Dave Ziebol


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 4:32 pm 
Newbie

Joined: Fri Oct 14, 2005 4:42 pm
Posts: 15
removed garbled message


Last edited by mikekonikoff on Fri Jul 14, 2006 4:33 pm, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 4:32 pm 
Newbie

Joined: Fri Oct 14, 2005 4:42 pm
Posts: 15
Quote:
There doesn't seem to be a way (that I've found yet) to push the retrieved ds or a connection requested from it into Hibernate...


This was already done by specifying the datasource property in the hibernate config file.

Quote:
What is the next step you do after getting your DataSource?


Build a session factory and open a session.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 5:02 pm 
Beginner
Beginner

Joined: Tue Sep 27, 2005 2:51 pm
Posts: 27
mikekonikoff wrote:
Quote:
There doesn't seem to be a way (that I've found yet) to push the retrieved ds or a connection requested from it into Hibernate...


This was already done by specifying the datasource property in the hibernate config file.

Quote:
What is the next step you do after getting your DataSource?


Build a session factory and open a session.

So then what becomes of your ds? I'm trying to accomplish this and getting confussed....

in my world... hibernate, oracle, Axis2,Tomcat...
in Tomcat \conf\Catalina\localhost\axis2.xml contains my context of
Code:
<?xml version='1.0' encoding='utf-8'?>
<Context crossContext="true" debug="5" docBase="axis2" path="/axis2" reloadable="true">
<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_axis2_log." suffix=".txt" timestamp="true"/>
    <Resource name="jdbc/foundationsDS" auth="Container" type="javax.sql.DataSource"/>
   <ResourceParams name="jdbc/foundationsDS">
   <parameter>
      <name>factory</name>
      <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
   </parameter>
   <parameter>
      <name>driverClassName</name>
      <value>JdbcOraWrapperDriver</value>
   </parameter>
   <parameter>
      <name>url</name>
      <value>jdbc:oracle:thin:@xxxxxxx:1234:xxxxx</value>
   </parameter>
   <parameter>
      <name>username</name>
      <value>username val</value>
   </parameter>
   <parameter>
      <name>password</name>
      <value>password val</value>
   </parameter>
   <!-- Maximum number of dB connections in pool. Make sure you configure your mysqld max_connections large enough to
   handle all of your db connections. Set to 0 for no limit. -->
   <parameter>
      <name>maxActive</name>
      <value>20</value>
   </parameter>
   <!-- Maximum number of idle dB connections to retain in pool. Set to -1 for no limit. See also the DBCP documentation on
    this and the minEvictableIdleTimeMillis configuration parameter. -->
   <parameter>
      <name>maxIdle</name>
      <value>10</value>
   </parameter>
   <!-- Maximum time to wait for a dB connection to become available in ms, in this example 10 seconds. An Exception is thrown
    if this timeout is exceeded. Set to -1 to wait indefinitely. -->
   <parameter>
      <name>maxWait</name>
      <value>-1</value>
   </parameter>
   <parameter>
      <name>removeAbandoned</name>
      <value>true</value>
   </parameter>
   <parameter>
      <name>removeAbandonedTimeout</name>
      <value>6000</value>
   </parameter>
   <parameter>
      <name>logAbandoned</name>
      <value>true</value>
   </parameter>
    </ResourceParams>
</Context>

my web.xml contains a reference to the resource as
Code:
   <resource-ref>
      <description>xyz</description>
      <res-ref-name>jdbc/foundationsDS</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
   </resource-ref>


and my hibernate.cfg.xml contains
Code:
   <property name="connection.data_source">java:comp/env/jdbc/foundationsDS</property>
   <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>   
      <property name="connection.driver_class">JdbcOraWrapperDriver</property>
   <property name="show_sql">true</property>


Then finally in my code I do the standard setup as
Code:
public class ServerHibernateUtil
{
   private static final Logger log = Logger.getLogger(ServerHibernateUtil.class);

   public ServerHibernateUtil()
   {
      super();
   }
   protected static String pathStr = new String("myEnvHibernate.cfg.txt");
   public static final SessionFactory sessionFactory;

   static
   {
      String whereAmI = ServerHibernateUtil.class.getName();
      try
      {
         
         Configuration c = new Configuration();
         
         c.addClass(abunchOClasses.class);
         c.configure();
         sessionFactory = c.buildSessionFactory();
      }
      catch (Throwable ex)
      {
         // Make sure you log the exception, as it might be swallowed
         String msg = new String();
         msg = whereAmI + " Initial SessionFactory creation failed."
               + ex.getMessage();
         log.error(msg);
         throw new IssueEncounteredException(
               new ExceptionInInitializerError(ex), msg);
      }
   }
   public static final ThreadLocal session = new ThreadLocal();

   public static Session currentSession() throws HibernateException
   {
      Session s = (Session) session.get();
      // Open a new Session, if this thread has none yet
      if (s == null)
      {
         s = sessionFactory.openSession();
         // Store it in the ThreadLocal variable
         session.set(s);
      }
      return s;
   }

   public static void closeSession() throws HibernateException
   {
      try
      {
         Session s = (Session) session.get();

         if (s != null)
            s.close();
         session.set(null);
         Thread.currentThread().dumpStack();
      }
      catch (Exception e)
      {

      }
   }
}


So are you saying that there is no need to create the datasource via
DataSource ds = InitialCont....

and the above ServerHibernateUtil "should" utilize the configured datasource?...

It doesn't, any ideas would be greatly appriated.

Thanks

_________________
Dave Ziebol


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 5:20 pm 
Newbie

Joined: Fri Oct 14, 2005 4:42 pm
Posts: 15
Quote:
So are you saying that there is no need to create the datasource via
DataSource ds = InitialCont....


Yes

Quote:
and the above ServerHibernateUtil "should" utilize the configured datasource?...

It doesn't, any ideas would be greatly appriated.


Looks like you might need:

c.configure(new File("<path to your hibernate.cfg.xml>");

instead of

c.configure();


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 5:47 pm 
Beginner
Beginner

Joined: Tue Sep 27, 2005 2:51 pm
Posts: 27
Code:
protected static String pathStr = new String("myEnvHibernate.cfg.txt");


is a copy and paste issue. the
Code:
   <property name="connection.data_source">java:comp/env/jdbc/foundationsDS</property>
   <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>   
      <property name="connection.driver_class">JdbcOraWrapperDriver</property>
   <property name="show_sql">true</property>


really does reside in a hibernate.cfg.xml file in the WEB-INF\classes directory.

But allas, I continue to encounter
"java.lang.UnsupportedOperationException: The user must supply a JDBC connection"

Any other ideas?

_________________
Dave Ziebol


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 6:19 pm 
Newbie

Joined: Fri Oct 14, 2005 4:42 pm
Posts: 15
I've only ever used the explicit path configure method, but I'm pretty sure you are correct that cfg file default path is WEB-INF/classes.

At the risk of stating the obvious, the property tags you quoted should be contained inside session-factory tags of the hibernate.cfg.xml file.

Code:
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration>
    <session-factory>
<property name="connection.data_source">java:comp/env/jdbc/foundationsDS</property>
   <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>   
      <property name="connection.driver_class">JdbcOraWrapperDriver</property>
   <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>


You may also need to give the full package name for the driver.

While it's not necessary to instantiate the DataSource object from your setup class, you could do it anyway just for a sanity check:

Code:
    InitialContext ctx = new InitialContext();
    DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/foundationsDS");
    Connection connection = ds.getConnection();
    java.sql.Statement statement = connection.createStatement();
    ResultSet resultset=statement.executeQuery("SELECT sysdate FROM dual");
    if (resultset.next()) out.println("Here is a query result of sysdate from dual: " + resultset.getString(1) + "<BR>");
    resultset.close();
    connection.close();


In any case you should check your tomcat logs for entries like:


Jul 14, 2006 6:10:12 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Jul 14, 2006 6:10:12 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1141 ms
Jul 14, 2006 6:10:12 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Jul 14, 2006 6:10:13 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/5.5.9
Jul 14, 2006 6:10:13 PM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
Jul 14, 2006 6:10:16 PM org.apache.catalina.session.PersistentManagerBase start
SEVERE: No Store configured, persistence disabled
Jul 14, 2006 6:10:17 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.0.3
Jul 14, 2006 6:10:17 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Jul 14, 2006 6:10:17 PM org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
Jul 14, 2006 6:10:17 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
.
.
.
Jul 14, 2006 6:10:41 PM org.hibernate.util.NamingHelper getInitialContext
INFO: JNDI InitialContext properties:{}
Jul 14, 2006 6:10:41 PM org.hibernate.connection.DatasourceConnectionProvider configure
INFO: Using datasource: java:comp/env/jdbc/<yourDSName>
Jul 14, 2006 6:10:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: <Your DB info>
Jul 14, 2006 6:10:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: <Your JDBC driver info>
Jul 14, 2006 6:10:41 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.OracleDialect
Jul 14, 2006 6:10:41 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
Jul 14, 2006 6:10:41 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
Jul 14, 2006 6:10:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
Jul 14, 2006 6:10:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
Jul 14, 2006 6:10:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
Jul 14, 2006 6:10:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: null
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 0
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
Jul 14, 2006 6:10:42 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: enabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: enabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory createQueryCacheFactory
INFO: Query cache factory: org.hibernate.cache.StandardQueryCacheFactory
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: enabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
Jul 14, 2006 6:10:42 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
Jul 14, 2006 6:10:42 PM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Jul 14, 2006 6:10:42 PM org.hibernate.cache.CacheFactory createCache
.
.
.
Jul 14, 2006 6:10:53 PM org.hibernate.cache.UpdateTimestampsCache <init>
INFO: starting update timestamps cache at region: org.hibernate.cache.UpdateTimestampsCache
Jul 14, 2006 6:10:53 PM org.hibernate.cache.StandardQueryCache <init>
INFO: starting query cache at region: org.hibernate.cache.StandardQueryCache
Jul 14, 2006 6:10:53 PM org.hibernate.impl.SessionFactoryImpl checkNamedQueries
INFO: Checking 0 named queries
Jul 14, 2006 6:10:53 PM org.apache.catalina.core.StandardHost start
INFO: XML validation disabled
Jul 14, 2006 6:10:53 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
Jul 14, 2006 6:10:53 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Jul 14, 2006 6:10:53 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/63 config=null
Jul 14, 2006 6:10:53 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 40828 ms

The logs should have at least some info that hibernate is starting up...otherwise your config is not set up properly.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jul 14, 2006 6:36 pm 
Beginner
Beginner

Joined: Tue Sep 27, 2005 2:51 pm
Posts: 27
Obvious is good... been burned by that many time before :-)
And I did a double take to insure I really saw them in the hibernate.cfg.xml file, they are there (<session-factory> tags)


>You may also need to give the full package name for the driver.
The JdbcOraWrapperDriver packaging is correct (there is none)

>While it's not necessary to instantiate the DataSource object from your setup class, you could do it anyway just for a sanity check:

Yep - sanity has been validated - if I access the datasource in a conventional manner - I can get a valid connection that I can run quries on and get results.

I'll have to turn on the hibernate logging again, and see if there is any mention of the datasource.

Thanks for all the feed back and assistence.

_________________
Dave Ziebol


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 18, 2006 2:52 pm 
Beginner
Beginner

Joined: Tue Sep 27, 2005 2:51 pm
Posts: 27
Still working on this...

annoying part is that while the message
Code:
59343 [http-8080-Processor25] WARN  org.hibernate.connection.UserSuppliedConnectionProvider  - No connection properties specified - the user must supply JDBC connections


is output, if I printout the session parmameters - on the list I find
Code:
cat 5.0\webapps\axis2
key value paring of hibernate.connection.data_source:java:/comp/env/jdbc/foundat
ionsDS

Code:
key value paring of connection.driver_class:JdbcOraWrapperDriver
key value paring of hibernate.connection.driver_class:JdbcOraWrapperDriver

key value paring of dialect:org.hibernate.dialect.Oracle9Dialect
key value paring of hibernate.dialect:org.hibernate.dialect.Oracle9Dialect

key value paring of connection.password:XXXXX
key value paring of hibernate.connection.password:XXXXXX

key value paring of hibernate.connection.username:XXXXX_user
key value paring of connection.username:XXXXX_user

key value paring of hibernate.connection.data_source:java:/comp/env/jdbc/foundat
ionsDS
key value paring of connection.data_source:java:/comp/env/jdbc/foundationsDS

Seems some of the values are getting into the keyValue pairings twice; once prefixed with hibernate and once without. I have since removed the

This is odd though
Code:
key value paring of java.naming.factory.initial:org.apache.naming.java.javaURLCo
ntextFactory


Within my code I have no problem programattically getting a datasource as follows:
Code:
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            if(envCtx == null )
               throw new Exception("Boom - No Environment Context");
//             the following matches the resource name defined in foo.xml
            DataSource ds = (DataSource) envCtx.lookup("jdbc/foundationsDS");
            String quest = new String("What is in my ds then???");
            log.debug(whereAmI + quest);
            
            if (ds != null)
            {
               Connection conn = ds.getConnection();


Any help would be greatly appreciated!

_________________
Dave Ziebol


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 18, 2006 5:16 pm 
Beginner
Beginner

Joined: Tue Sep 27, 2005 2:51 pm
Posts: 27
Based on the information fount in
http://forums.hibernate.org/viewtopic.php?t=945711&highlight=datasource+cfg+setproperties&sid=ece6139649c4bb711b4204265b894ef7

I tried
Code:
         System.setProperty("hibernate.connection.datasource", "java:/comp/env/jdbc/foundationsDS");
         c.setProperties(System.getProperties());

         c.configure();


And I'm now able to secure connections from the datasource.

If I find the reason for the above issue, I'll post. If anyone else finds a reason, please post and I'll be notified.

Thanks for everyones assistence

_________________
Dave Ziebol


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 12 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.