Salem's Euphoria

Sharing Experience

1 Comment

Dynamic Hibernate Context Switching

 Dynamic context switching

Commonly, in a web application, only one database is needed.  On a J2EE application, the context defined in the webApplicationContext.xml is a static configuration file with one database(as far as I know). Furthermore, we need Associating entities through mapping files(hbm.xml) or with directly annotated classes.  But what if we need to create databases dynamically and switch between them?
This approach, dynamic DB creation, may have its drawbacks, but it may be a fatality in some cases.

Here is a demonstration of dynamic database creation and dynamic context switching.

First , we need the database creation script(create_script.sql).

'id' int(11) NOT NULL auto_increment,
'name' varchar(20) default NULL,
'country' varchar(100) default NULL,
'adress' VARCHAR(20) default NULL,

And then create the database manually given its name:

java.sql.Connection connection = null;
     connection=DriverManager.getConnection("[jdbc:mysql://dbserver:port]",user, pwd);
     java.sql.Statement stm=connection.createStatement();
     stm.executeUpdate(" CREATE DATABASE "+myDbName);
     String[] cmd = new String[]{"mysql", myDbName,
     "--user= "+user,
     "--password="+root ,
     "\"source  [fullPathto]\\create_script.sql\""
     Runtime rt = Runtime.getRuntime>();
     Process proc = rt.exec(cmd);
}catch(Exception e){

I used MySql in this sample, thus, it should be in path environment variable. User and pwd variables are your server specific username and password. The fullPathTo is the full path directory to your create_table.script.

The database now created and populated, we have to make it accessible through a hibernate Context. I prefer using annotation for mapping but it can also been done with xml mapping files.  The context template looks like (hbtConf.xml):

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    <property name="connection.url">
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">
    <property name="dialect">
    <property name="current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <property name="configurationClass">
    <mapping class="com.slm.entity.Person" />

Note that the “connection.url” was not set intentionally, it will be set later on the code while loading the context.

And here our person class :

@Table(name = "person")
public class Organisme implements Serializable {
private static final long serialVersionUID = 10L;
@Basic(optional = false)
@Column(name = "id")
private String id;
@Column(name = "name")
private String name;

@Column(name = "country")
private String country;

@Column(name = "adress")
private String adress;

//constructor, getters and setters, equal and hash …


Now, we’ll load the Annotated Configuration file, and set the connection.url property to fit our newly created database.

SessionFactory sf = null;
Session ss = null;
    Configuration conf =new AnnotationConfiguration().
    conf.setProperty("hibernate.connection.url", serverRoot+myDbName);
    sf = conf.buildSessionFactory();
    ss = sf.getCurrentSession();
}catch (Exception e) {
    logger.error("session creation problem \nMSG:" +e.getMessage()+ "\nCause: " + e.getStackTrace().toString());

Setting the hibernate.connection.url manually to the new destination would select the intended database. You may have other properties to set manually if you’re using Lucene indexes for example:

   conf.setProperty("", indexRootFolder + myContextualIndexDirectoryName);

That’s all for dynamic context switching.


Leave a comment

Google Maps , Flex and JSP

The sample application provided on this post explains a simple way of using Google Maps API on Flex to mark some places and add a discription to the Marker.

Google Maps & JSP

Google Maps API Sample

To use the jsp, we first define a HttpService objet in our MXML  with a result and an error handler:

<mx:HTTPService id="saveCoordSrv"

then we need a model for our entity to manage , I preferred to make it binded to input fields(inAdress,inLat,…):

<!-- The marker model -->
<mx:Model id="coordToSave">

and then just make the call :


In the insert JSP, we just collect sent params using request.getParameter(“param_name”) :

String adr = request.getParameter("adress");
String lat = request.getParameter("lat");

and then manipulate your database driver to make an insert/delete/update query. In this sample i used MySql.

Next time we’ll be discussing google maps events use.  If you need any explanation about the code, please do not hesitate 🙂

Send me an email ( to get Source Code(I uploaded it in many providers but links are dead).