Thursday, March 13, 2014

Hibernate quick start guide(with Eclipse).

I used, at now, the latest versions of...
Eclipse Kepler for JavaEE developer
Hibernate ORM 4.3.4
Java 6
MySQL 5.5(more mysql connector... download here)
...all installed on my Debian Wheezy...

Here's a smart guide to create a very small project for Hibernate capabilities.

For Hibernate ORM 4.3.4 resources file, please refer to official site for download latest version.

1) Eclipse: create a new Java Project.

2) Add in the classpath(right click on the project -> properties -> Java Build Path -> Libraries -> Add external libraries) the libraries contained into the hibernate zip file(currently is hibernate-release-4.3.4.Final.zip) you download. You can put only the contents of the "required" folder.

3) Add in the classpath the mysql-connector_XXX.jar(from here) depends of the version of your db version and of connector version....

4) Into src folder create the bean class that maps the persistent object

package com.bean;


import java.io.Serializable;
import java.lang.String;

/**
 * Entity implementation class for Entity: User
 * @author Maurizio Franco
 *         http://maurizio-franco.blogspot.it
 *         maurizio.franco@ymail.com
 */
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
   
    private int id;
   
    private String username;
    private String password;
    private String email;
   

    public User() {
        super();
    }  
    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }  
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }  
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }  
    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
  
}


5) Here is the table script....

CREATE TABLE Users (
               id INT(5) NOT NULL AUTO_INCREMENT,
               username VARCHAR(20) NOT NULL,
               email    VARCHAR(40) NOT NULL,
               password VARCHAR(20) NOT NULL,               
               PRIMARY KEY(id) 

);

6) Then the class thats provides to test the insert of data....

package com.test;

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.Configuration;

import com.bean.User;



/**
 *
 * Test class, to run simple database operations...
 *
 * @author Maurizio Franco
 *         http://maurizio-franco.blogspot.it
 *         maurizio.franco@ymail.com
 */
public class StoreData {

    public static void main(String[] args) { 
        System.out.println("StoreData - START");
        //creating configuration object 
        Configuration cfg=new Configuration();
        //populates the data of the configuration file
        cfg.configure("hibernate.cfg.xml"); 
         
        //creating seession factory object 
        SessionFactory factory=cfg.buildSessionFactory(); 
         
        //creating session object 
        Session session=factory.openSession(); 
         
        //creating transaction object 
        Transaction t=session.beginTransaction(); 
             
        User e1=new User(); 
        e1.setUsername("usernamexxx"); 
        e1.setPassword("pwdxxx");
        e1.setEmail("mail@xxxx");
         
        session.persist(e1);//persisting the object 
         
        t.commit();//transaction is committed 
        session.close(); 
         
        System.out.println("StoreData - successfully saved");           
    } 

}




7) Now under the src folder you have to create two configuration files.
The first map the bean/persistent object. It's user.hbm.xml
Note that here we map the com.bean.User to the Users table.

<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-mapping PUBLIC   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
 
 <hibernate-mapping> 
  <class name="com.bean.User" table="Users"> 
    <id name="id"> 
     <generator class="assigned"></generator> 
    </id> 
           
    <property name="username"></property> 
    <property name="password"></property>
    <property name="email"></property> 
           
  </class> 
           
 </hibernate-mapping>


8) the other configuration file maps contains database connection info.
Also this is under the src folder. It's hibernate.cfg.xml

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

 
<hibernate-configuration> 
 
    <session-factory> 
        <property name="hbm2ddl.auto">update</property> 
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 
        <property name="connection.url">jdbc:mysql://localhost:3306/your_db_name</property> 
        <property name="connection.username">your_username</property> 
        <property name="connection.password">your_password</property> 
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
    <mapping resource="user.hbm.xml"/> 
    </session-factory> 
 
</hibernate-configuration>


That's all.... or not?? Remember to customize your hibernate.cfg.xml....
in connection.url, connection.username and connection.password properties....

Execute the main method of StoreData class....
It will provides the simple insert operation...

You can find a small project(contains all you have seen up to here) into a branch of sourceforce.net svn.
It's ready to use...

The url is:
svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithHibernate/trunk/StartingWithHibernate
And the istructions from command line are:
svn checkout svn://svn.code.sf.net/p/mauriziofranco/code/StartingWithHibernate/trunk/StartingWithHibernate  mauriziofranco-code

Bye..

No comments:

Post a Comment