Convert JDBC code in to Hibernate

Welcome to my new article on convert jdbc code to Hibernate.

If you want to convert your J2ee application developed using JDBC into hibernate you landed in the correct place. This practical example will help you to convert JDBC Code to use hibernate as the ORM package which benefits your application:
  • Helps to abstract the persistence of the object.
  • Powerful hibernate query language (HQL).
  • The developer free from the headaches of connection pooling, connection management etc.
in order to convert your application to use hibernate, follow the following steps,

1. Add the following jars to your library.

 hibernate-3.3.2.GA_CP03.jar
 javaee-api-6.0.jar
 dom4j-1.6.1.jar
 jta-1.3.jar
 
2. Update your configuration files.

Update spring beans configuration file using apache commons for configurations. I used apache commons library for my project.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>
 
Update jdbc transaction manager to use the hibernate transaction manager.
The following is the code my file has
 
<bean id="transactionManager" 
     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

This we can replace using the below given code

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
   <props>
 <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
       <prop key="hibernate.show_sql">true</prop>
       </props>
</property>
<property name="mappingResources">
<list>
<value>passwordvault/domain/hibernate/Password.hbm.xml</value>
 </list>
</property>
 
 
I am using postgresql database so the corresponding sql dialect is org.hibernate.dialect.PostgreSQLDialect, To create Hibernate template instance we need a Session Factory, for this purpose we injecting the sessionFactory property in the Spring bean configuration file.

    <bean id="passwordDao" class="passwordvault.repository.PasswordDaoImpl" >
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
 
 
3. Model files mapping

You have to create hibernate mapping file to use hibernate. This mapping file will maps your domain class and the tables. This will have the name ending with hbm.xml. For example if your domain class have the name Password.java your mapping file name you can keep as Password.hbm.xml You have the right to chose the right name for the mapping file.

See the Password.hbm.xml file here

     <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="passwordvault.domain.Password" 
        table="pw.password" >
        <id name="id" type="integer">
            <column name="id" />
        <generator class="sequence">
         <param name="sequence">pw.pw_seq</param>
        </generator> 
        </id>
        <property name="password" type="string">
            <column name="PW_PASSWORD" length="100" not-null="true" />
        </property>
        <property name="source" type="string">
            <column name="PW_SOURCE" not-null="true" />
        </property>
        <property name="userName" type="string">
            <column name="PW_USERNAME" length="100" not-null="true" />
        </property>
         <property name="remarks" type="string">
            <column name="remarks" length="500" not-null="true" />
        </property>
    </class>
</hibernate-mapping>
This corresponds to the model class Password.java
package passwordvault.domain;
import java.io.Serializable;
public class Password  implements Serializable {
     private int id;
    private String password;
     private String source;
    private String userName;
     private String remarks;
   public int getId() {

   return id;

  }
  public String getRemarks() {
   return remarks;
  }
  public void setRemarks(String remarks) {
   this.remarks = remarks;
  }
  public void setId(int id) {

   this.id = id;

  }
  public String getPassword() {

   return password;

  }
  public void setPassword(String password) {
   this.password = password;
  }
  /**
   * @return the source
   */
  public String getSource() {
   return source;
  }
  /**
   * @param source the source to set
   */
  public void setSource(String source) {
   this.source = source;
  }
  /**
   * @return the userName
   */
  public String getUserName() {
   return userName;
  }
  /**
   * @param userName the userName to set
   */
  public void setUserName(String userName) {
   this.userName = userName;
  }
 }
It is common in a typical J2EE application will have a number of model classes so you need to have the corresponding mapping file as explained above.
You can follow the annotation base configuration I am explained here.
 
4. Changes in the DAO class 

In the DAO class we use Hibernate Template to access the database. Extend the HibernateDaoSupport calss in the DaoImpl class to make your DAO class to eligible for the hibernate usage.

public class PasswordDaoImpl  extends HibernateDaoSupport implements PasswordDao {


the method used by JDBC method need to change to use the hibernate template and you can use powerfu Hibernate SQL query language in your code,

/*Old method 1-*/
  public List getPasswordListOld() {
        List pw = this.jdbcTemplate.query(
                "select id pwid, PW_PASSWORD,PW_SOURCE,PW_USERNAME,remarks from pw.PASSWORD order by PW_SOURCE asc", 
                new PasswordMapper());
        return pw;
    }
    /*this will be the new method*/
    public List getPasswordList() {
        
        return getHibernateTemplate().find("from pw.PASSWORD");
    }
/*Old method 2-*/
    public void savePasswordOld(Password pw) {
     
        logger.info("Saving password for the source: " + pw.getSource());
        int count = this.jdbcTemplate.update(
        "insert into pw.password (id, pw_source, pw_username,pw_password,remarks) values( nextval('pw.pw_seq'),?,?,?,?)",
        new Object[] {pw.getSource(),pw.getUserName(),pw.getPassword(),pw.getRemarks()});
    }
        /*This will be the new method*/
    public void savePassword(Password password) {
     
        logger.info("Saving password for the source: " + password.getSource());
        getHibernateTemplate().save(password);
    }
--------------------------------
Trouble shooting

After the above errors I got the error related to jar or class not found error, I resolved by adding the above mentioned jar files, so its working perfectly

Thank you, Please post your comments below

Related Posts

Comments

  1. You used postgre sql as the driver, can I use mysql driver also insteda of this?

    ReplyDelete

Post a Comment

Please type your comments here