Monthly Archives: November 2010

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).

CREATE TABLE 'Person' (
'id' int(11) NOT NULL auto_increment,
'name' varchar(20) default NULL,
'country' varchar(100) default NULL,
'adress' VARCHAR(20) default NULL,
PRIMARY KEY  ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And then create the database manually given its name:

java.sql.Connection connection = null;
try{
     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 ,
     "-e",
     "\"source  [fullPathto]\\create_script.sql\""
     };
     Runtime rt = Runtime.getRuntime>();
     Process proc = rt.exec(cmd);
     proc.waitFor();
}catch(Exception e){
     logger.fatal(e.getMessage());
}

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"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="connection.url">
      XXX
    </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.MySQLInnoDBDialect
    </property>
    <property name="current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <property name="configurationClass">
      org.hibernate.cfg.AnnotationConfiguration
    </property>
    <mapping class="com.slm.entity.Person" />
</session-factory>
</hibernate-configuration>

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 :

@Entity
@Table(name = "person")
public class Organisme implements Serializable {
private static final long serialVersionUID = 10L;
@Id
@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;
try{
    Configuration conf =new AnnotationConfiguration().
    configure("hbtConf.xml");
    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("hibernate.search.default.indexBase", indexRootFolder + myContextualIndexDirectoryName);

That’s all for dynamic context switching.

Advertisements

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"
url="http://[server:port]/googleMapToMySql/insert.jsp"
result="handleListResult(event)"
fault="errorFault(event)"/>

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">
	<root>
            <adress>{inAdress.text}</adress>
            <lat>{inLat.text}</lat>
            <lng>{inLng.text}</lng>
            <commentaire>{inComment.text}</commentaire>
	</root>
</mx:Model>

and then just make the call :

saveCoordSrv.send(coordToSave);

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 (salemba@live.fr) to get Source Code(I uploaded it in many providers but links are dead).

Hello WordPress!

This is my first time on wordpress and i’ll try to report my own experience. First of all, I apologize from all readers for my bad english, and i’ll try to write in english, french and arabic sometimes.