-->
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.  [ 11 posts ] 
Author Message
 Post subject: Dynamic configuration
PostPosted: Wed Jun 06, 2007 4:31 am 
Beginner
Beginner

Joined: Sat May 12, 2007 2:55 am
Posts: 24
Hibernate version:3.1

Hi friends.

i am newbie to HN and wanted to know that how can we configure the database specific settings using dynamic configuration. generally we are mentioning something like below in hibernate.cfg.xml and in sessionfactory we are using these settings.

<property name="connection.url">jdbc:mysql://localhost:3306/testdb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect"> org.hibernate.dialect.MySQLDialect
</property>



the question is what if i want to provide username/password and database name dynamically...
where should i write the content....
if a small example is provided that would be a big help :)

thanks in advance..


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 5:43 am 
Senior
Senior

Joined: Thu May 17, 2007 2:31 am
Posts: 194
Location: Sri Lanka
Hi


you can do it by using a utility class.

Code:
private void init(HibernateConfig poHibernateConfig)throws MappingException,HibernateException {
       
        hibernateConfig=poHibernateConfig;
         
        Configuration confg = new Configuration();       
        confg.setProperty("hibernate.connection.driver_class","net.sourceforge.jtds.jdbc.Driver");
        confg.setProperty("hibernate.connection.url","jdbc:jtds:sqlserver://"+hibernateConfig.getSqlServerName()+":" +hibernateConfig.getPort()  +"/" + hibernateConfig.getDatabaseName());
        confg.setProperty("hibernate.connection.username",hibernateConfig.getUserName());
        confg.setProperty("hibernate.connection.password",hibernateConfig.getPassword() );       
        confg.setProperty("hibernate.dialect","org.hibernate.dialect.SQLServerDialect");
        confg.setProperty("hibernate.connection.pool_size",""+hibernateConfig.getPoolSize());
       
        if(hibernateConfig.isCacheEnabled()){
           confg.setProperty("hibernate.cache.provider_class","org.hibernate.cache.OSCacheProvider");
           confg.setProperty("hibernate.cache.provider_configuration_file_resource_path","/ehcache.xml");
        } else{           
            confg.setProperty("hibernate.cache.provider_class","org.hibernate.cache.NoCacheProvider");
        }
       
       
       
        confg.setProperty("hibernate.current_session_context_class","thread");
       
        confg.setProperty("hibernate.jdbc.use_scrollable_resultset","true");
        if(hibernateConfig.isShowSQL()){
           confg.setProperty("hibernate.show_sql","true");
        }
       
        logger.debug("Hibernate properties config done.");       
        try{
              
   
           
                             
           confg.addClass(Address.class);
           confg.addClass(Person.class);
           confg.addClass(Employee.class);                       
            sessionFactory = confg.buildSessionFactory();         
                       
         Session s = sessionFactory.openSession();
         
         if(s.connection()==null){      
                        throw new HibernateException("SQL Connection Error SQLSERVER= "+hibernateConfig.getSqlServerName()+" Database Name= "+hibernateConfig.getDatabaseName());            
         }         
         s.close();
                 } catch (MappingException e) {
                       throw e;
        } catch (HibernateException e) {
                       throw new HibernateException(e.getCause());
        }
       
    }


in here HibernateConfig is a config class for dynamic data



Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject: RE:utility class.
PostPosted: Wed Jun 06, 2007 6:18 am 
Beginner
Beginner

Joined: Sat May 12, 2007 2:55 am
Posts: 24
amila733 wrote:
Hi

thanks for very fast reply..
i am trying your suggestion but unable to resolve what is hibernateConfig.
also shall i vacant my hibernate.cfg.xml file as all that stuff we are writing here..

you can do it by using a utility class.

Code:
private void init(HibernateConfig poHibernateConfig)throws MappingException,HibernateException {
       
        hibernateConfig=poHibernateConfig;
         
        Configuration confg = new Configuration();       
        confg.setProperty("hibernate.connection.driver_class","net.sourceforge.jtds.jdbc.Driver");
        confg.setProperty("hibernate.connection.url","jdbc:jtds:sqlserver://"+hibernateConfig.getSqlServerName()+":" +hibernateConfig.getPort()  +"/" + hibernateConfig.getDatabaseName());
        confg.setProperty("hibernate.connection.username",hibernateConfig.getUserName());
        confg.setProperty("hibernate.connection.password",hibernateConfig.getPassword() );       
        confg.setProperty("hibernate.dialect","org.hibernate.dialect.SQLServerDialect");
        confg.setProperty("hibernate.connection.pool_size",""+hibernateConfig.getPoolSize());
       
        if(hibernateConfig.isCacheEnabled()){
           confg.setProperty("hibernate.cache.provider_class","org.hibernate.cache.OSCacheProvider");
           confg.setProperty("hibernate.cache.provider_configuration_file_resource_path","/ehcache.xml");
        } else{           
            confg.setProperty("hibernate.cache.provider_class","org.hibernate.cache.NoCacheProvider");
        }
       
       
       
        confg.setProperty("hibernate.current_session_context_class","thread");
       
        confg.setProperty("hibernate.jdbc.use_scrollable_resultset","true");
        if(hibernateConfig.isShowSQL()){
           confg.setProperty("hibernate.show_sql","true");
        }
       
        logger.debug("Hibernate properties config done.");       
        try{
              
   
           
                             
           confg.addClass(Address.class);
           confg.addClass(Person.class);
           confg.addClass(Employee.class);                       
            sessionFactory = confg.buildSessionFactory();         
                       
         Session s = sessionFactory.openSession();
         
         if(s.connection()==null){      
                        throw new HibernateException("SQL Connection Error SQLSERVER= "+hibernateConfig.getSqlServerName()+" Database Name= "+hibernateConfig.getDatabaseName());            
         }         
         s.close();
                 } catch (MappingException e) {
                       throw e;
        } catch (HibernateException e) {
                       throw new HibernateException(e.getCause());
        }
       
    }


in here HibernateConfig is a config class for dynamic data



Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 6:40 am 
Senior
Senior

Joined: Thu May 17, 2007 2:31 am
Posts: 194
Location: Sri Lanka
Hi

yes. You don't want hibernate config xml file anymore


HibernateConfig is a my own config file . it is used to pass config properties to init method. we can change database settings and other hibernate config settings in dynamically by passing new HibernateConfig object to init method


Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject: Re: RE:utility class.
PostPosted: Wed Jun 06, 2007 7:28 am 
Beginner
Beginner

Joined: Sat May 12, 2007 2:55 am
Posts: 24
Hi,
i am placing my HibernateSessionFactory.java and my hibernate.cfg.xml
if u can figure out where i am wrong in dynamic configuration.
(right now trying static data, but not in hibernate.cfg.xml)

HibernateSessionFactory.java
-----------------------------------------------
package com;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;


public class HibernateSessionFactory {


private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

private HibernateSessionFactory() {
}


public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

public static void rebuildSessionFactory() {
try {
//configuration.configure(configFile); //original and working
//******** dynamic code where there is a problem

Properties prop = new Properties();
prop.setProperty("hibernate.connection.username","root");
prop.setProperty("hibernate.connection.password","root");
prop.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLDialect
");
prop.setProperty("hibernate.connection.pool_size","10");
prop.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
prop.setProperty("connection.url","jdbc:mysql://localhost:3306/testdb");
prop.setProperty("hbm2ddl.auto", "update");
configuration.setProperties(prop);
configuration.addResource("Login.hbm.xml");
configuration.addResource("User.hbm.xml");
sessionFactory = configuration.buildSessionFactory();

//*********************

sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}


public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}


public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}


public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}


public static Configuration getConfiguration() {
return configuration;
}

}




and
Hibernate.cfg.xml (The working one - hardcoded sample)
-----------------------------

<?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">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

<session-factory>
<property name="myeclipse.connection.profile">
cpvdbdemo
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/testdb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="model/User.hbm.xml" />
<mapping resource="model/Login.hbm.xml" />
</session-factory>

</hibernate-configuration>


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 7:41 am 
Senior
Senior

Joined: Thu May 17, 2007 2:31 am
Posts: 194
Location: Sri Lanka
Hi

in your code there is sessionFactory = configuration.buildSessionFactory() ; twise.


can you send top of your print stack for more detail.


Amila


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 7:57 am 
Beginner
Beginner

Joined: Sat May 12, 2007 2:55 am
Posts: 24
yes it was mistakenly pasted twice.....

and the exceptions i am getting is something like.....


%%%% Error Creating SessionFactory %%%%
org.hibernate.MappingException: Could not read mapping document from file: Login.hbm.xml
at org.hibernate.cfg.Configuration.addFile(Configuration.java:252)
at demo.factory.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:69)
at demo.factory.HibernateSessionFactory.getSession(HibernateSessionFactory.java:45)
at demo.dao.UserDAO.selectAllUsers(UserDAO.java:15)
at demo.action.UserListAction.execute(UserListAction.java:41)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


thanks for sparing time.

nirav

amila733 wrote:
Hi

in your code there is sessionFactory = configuration.buildSessionFactory() ; twise.


can you send top of your print stack for more detail.


Amila


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 8:03 am 
Senior
Senior

Joined: Thu May 17, 2007 2:31 am
Posts: 194
Location: Sri Lanka
Hi

it is because of rong location of .hbm.xml files. I see that in your previoues cfg.xml mapping files at model/User.hbm.xml but in your new code it is only User.hbm.xml . that is the cause.

You can write

configuration.addClass(A.class) instead of this
configuration.addResource("Login.hbm.xml");

in here your mapping files should with your .class files


Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 8:39 am 
Beginner
Beginner

Joined: Sat May 12, 2007 2:55 am
Posts: 24
Hi i tried out the suggested one. but is giving the same exception.
but surprisingly when i commented all the code related to resource addition , it is working !!! can you figure out how it is possible?
here is my latest code....

configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("connection.url","jdbc:mysql://localhost:3306/demo");
configuration.setProperty("hibernate.connection.username","root");
configuration.setProperty("hibernate.connection.password","root");
configuration.setProperty("hibernate.dialect","org.hibernate.dialect.SQLServerDialect");
configuration.setProperty("hibernate.connection.pool_size","10");
//configuration.addFile("Login.hbm.xml");
//configuration.addFile("User.hbm.xml");
//configuration.addClass(Login.class);
//configuration.addClass(User.class);
configuration.configure();



amila733 wrote:
Hi

it is because of rong location of .hbm.xml files. I see that in your previoues cfg.xml mapping files at model/User.hbm.xml but in your new code it is only User.hbm.xml . that is the cause.

You can write

configuration.addClass(A.class) instead of this
configuration.addResource("Login.hbm.xml");

in here your mapping files should with your .class files


Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 8:45 am 
Senior
Senior

Joined: Thu May 17, 2007 2:31 am
Posts: 194
Location: Sri Lanka
Hi

don't use both configuration.addFile("Login.hbm.xml");
and configuration.addClass(Login.class);

i think your hibernate.cfg.xml is still there . remove it and see what will happened.

and set only configuration.addClass(Login.class);


Amila

(Don't forget to rate if helps)


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 06, 2007 9:19 am 
Beginner
Beginner

Joined: Sat May 12, 2007 2:55 am
Posts: 24
it has been commented out, physically its there but is no more being used in the code.....

and also i have commeted
configuration.addFile("Login.hbm.xml");
and configuration.addClass(Login.class); both ...
now it is working...

thanks



amila733 wrote:
Hi

don't use both configuration.addFile("Login.hbm.xml");
and configuration.addClass(Login.class);

i think your hibernate.cfg.xml is still there . remove it and see what will happened.

and set only configuration.addClass(Login.class);


Amila

(Don't forget to rate if helps)


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 11 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.