Vivek

Wednesday, 13 November 2013

Create the Simple XMl based mapping Hibernate Application in Eclipse IDE

Simple basic step to  create a simple XML based example of hibernate application using eclipse IDE. For creating the hibernate application in Eclipse IDE, we need to follow following steps:
  1. Create the java project
  2. Add jar files for hibernate
  3. Create the Persistent class
  4. Create the mapping file for Persistent class
  5. Create the Configuration file
  6. Create the class that retrieves or stores the persistent object
  7. Run the application

Step-1 Create the java project.

Create the java project by File Menu - New - project - java project . Now specify the project name e.g. DemoHb then next finish .

Step-2 Add jar files in your class path for hibernate.

To add the jar files Right click on your project - Build path - Add external archives. and  select  all the jar files as shown in the image given below then click ok button .

     you can download library from given link..


Step-3 Create the Persistent class

To create the persistent class, Right click on src - New - Class - specify the class with package name (e.g. com.demo.vivekdemo) click finish button.

Employee.java


package com.demo.vivekdemo;
public class Employee{  
        private int id;  
       private String firstName, lastName; 
                 public int getId() {
                       return id;  
                  }
                 public void setId(int id) {
                       this.id = id;
                 }
                 public String getFirstName() {
                      return firstName;
                }
                public void setFirstName(String firstName) {
                     this.firstName = firstName;
                }
                public String getLastName() {
                     return lastName;
               }
               public void setLastName(String lastName) {
                    this.lastName = lastName;
               }
   }  

Step-4 Create the mapping (XML) file for Persistent class

Create the mapping file, Right click on src - new - file - specify the file name (e.g. employee.hbm.xml) click ok. It must be outside the package.

employee.hbm.xml

<?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.javatpoint.mypackage.Employee" table="emp1000">
    <id name="id">
           <generator class="assigned"></generator>
    </id>
         
    <property name="firstName"></property>
    <property name="lastName"></property>
         
  </class>
         
 </hibernate-mapping> 


Step-5 Create the Configuration file(it is like mysql-ds.xml file for normal JDBC connection )

The configuration file contains all the information for the datbase such as connection_url,  driver_class, username, password etc. The hbm2ddl.auto property is used to create the table in the database automatically. To create the configuration file, right click on src - new - file. Now specify the configuration file name (e.g. hibernate.cfg.xml) click ok button.

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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your-database-name</property>          
            <property name="hibernate.connection.username">your-mysql-user-id</property
            <property name="hibernate.connection.password">your-mysql-password</property>
            <mapping resource="employee.hbm.xml"/> 
  </session-factory>  
 </hibernate-configuration>  



Step-6 Create the class that retrieves or stores the persistent object (From database)



In this class, we are simply storing the employee object to the database.

package com.demo.vivekdemo;

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

public class StoreData {
      public static void main(String[] args) {
   
      Configuration cfg=new Configuration(); // create configuration object
      cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
      SessionFactory factory=cfg.buildSessionFactory(); //creating seession factory object
      Session session=factory.openSession();  //creating session object
      Transaction t=session.beginTransaction(); //creating transaction object
      Employee e1=new Employee();
      e1.setId(001);
      e1.setFirstName("Vivek");
      e1.setLastName("Rai");

      session.persist(e1);//persisting the object        t.commit();//transaction is commited        session.close();        System.out.println("successfully saved");
   }
 
}

Step-7 Run the application

See the output
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
successfully saved




No comments:

Post a Comment