Pages Navigation Menu

Coding is much easier than you think

Generic Hibernate Application Requirements – XML Mapping

Posted by in Hibernate, Hibernate XML Mapping

Hibernate Generic Requirment
 
The objective of this example is to understand the general requirement to be followed in creating any hibernate application in Java. You may want to look at Hibernate Installation/Setup on Eclipse IDE article if Hibernate is not installed already on your system.
 
In general any hibernate application, must have the following 4 files,

Model class
Mapping XML
Configuration XML
One java file to access this configuration file/write our logic

These files are the minimum requirement to run an hibernate application, in case of complex application we may require many Model classes and many mapping xml files, one configuration xml and a java program to access the configuration details and to write our logic.

Note : Number of Model classes = Number of mapping xml files
 

Model class

 
Model class is simple POJO (Plane old java object), that does extend any class or implement any interface, for each member variable defined in this class you must create a getter and a setter.
 
Example:Student.java
 

package model;

public class Student {
	private int id;
	private String name;
	private String department;
	private String college;

// Create Getters and Setters
}

 

Hibernate Mapping file for Model Class

 
The mapping file is where the Hibernate mapping comes into play, this mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
 
Student.hbm.xml : A simple hibernate XML mapping
 

<?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="model.Student" table="STUDENT">
		<id name="id" column="STUDENT_ID">
			<generator class="assigned" />
		</id>
		<property name="name" column="STUDENT_NAME" />
		<property name="department" />
		<property name="college" />
	</class>
</hibernate-mapping>

 
As shown above, the mapping file contains several elements, listed below are its role:

  • Class element takes care of mapping Student class from java side to STUDENT table in the database
  • Id element, indicates which column in database table we need to take as primary key column.
    In the property name of “id” element we need to give the member variable name from the student class(id) which will mapped with STUDENT_ID column in the STUDENT table.
     
    In the above example “id” member variable of Student class is mapped with STUDENT_ID Column of database, and this STUDENT_ID is the primary key of the table STUDENT.
     
    Note:
    I will explain about this <generator />element later.
     
  • Property element, used from non-primary key mapping , in this example name member variable is mapped to “STUDENT_NAME” of STUDENT table.
     
    Question: Why does id and name property mapping include the column attribute, but the department and college does not?
    Answer: Without the column attribute, Hibernate by default uses the property name as the column name. This works for department and college , however if we have a member variable called date in java class, now this date is a reserved keyword in most of the database, so you will need to map it to a different name, so in such scenarios we can go for column attribute in xml mapping.

 

Hibernate Configuration file

 
In this mapping file Hibernate gets to know about the type of database and its connection properties as well as about the mapping files.
 
File: hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
   <!-- Database connection settings -->
   <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
   <property name="hibernate.connection.username">system</property>
   <property name="hibernate.connection.password">admin</property>
   <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>

   <!-- SQL dialect -->
   <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

   <!-- Echo all executed SQL to sysout -->
   <property name="show_sql">true</property>

   <!-- Create/Update the database schema on startup -->
   <property name="hibernate.hbm2ddl.auto">update</property>
   <!-- Mapping file -->
   <mapping resource="Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

 
In our next article we shall learn about Generic Steps to be followed to use Hibernate in any Java application, going forward using this two articles we shall implement Hello World example of Hibernate 4 in Eclipse

Read More

Hibernate 4 Hello World example in Eclipse using XML Mapping

Posted by in Hibernate, Hibernate XML Mapping

Hibernate Hello world
 
This is the 4th article on Hibernate in java application that describes on how to to save an object from java into the database using Hibernate 4(Hibernate 4 Insert Query). If you have not read my previous articles article on Generic Hibernate Application Requirements (XML Mapping) and Steps to be followed to use Hibernate in Java, I will recommend that you read that article first. You may want to look at Hibernate Installation/Setup on Eclipse IDE article if Hibernate is not installed already on your system.
 
As described earlier, the following files are the minimum requirement to shape an hibernate program..

Student.java (Model class)
Student.hbm.xml  (Xml mapping file )
hibernate.cfg.xml  (Xml configuration file)
HibernateUtil.java (Main class to write hibernate logic)

 

Project Structure


 
The final appearance of the application should be as follows:
 
HibernateHelloWorld
 

Model class

 
Example:Student.java
 

package model;

public class Student {
	private int id;
	private String name;
	private String department;
	private String college;

// Create Getters and Setters
}

 

Hibernate Mapping file for Model Class

 
Now Create a new XML file(Student.hbm.xml) which is our mapping file related to above model class and place it in the src directory of your project.
 
Student.hbm.xml : A simple hibernate XML mapping
 

<?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="model.Student" table="STUDENT">
		<id name="id" column="STUDENT_ID">
			<generator class="assigned" />
		</id>
		<property name="name" column="STUDENT_NAME" />
		<property name="department" />
		<property name="college" />
	</class>
</hibernate-mapping>

 
Note: I have explained about each and every element used in the above file in the article Generic Hibernate Application Requirements
 

Hibernate Configuration file

 
Create a new XML file and give this new configuration file the default name hibernate.cfg.xmland place it src directory of your project.
 
File: hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
   <!-- Database connection settings -->
   <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
   <property name="hibernate.connection.username">system</property>
   <property name="hibernate.connection.password">admin</property>
   <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>

   <!-- SQL dialect -->
   <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

   <!-- Echo all executed SQL to sysout -->
   <property name="show_sql">true</property>

   <!-- Drop and re-create the database schema on startup -->
   <property name="hibernate.hbm2ddl.auto">create</property>
   <!-- Mapping file -->
   <mapping resource="Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

Hibernate Utility

 
Create the Main class to run the example.
 

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import model.Student;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();
		Student std = new Student();
		std.setId(1);
		std.setName("Jamil");
		std.setDepartment("ECE");
		std.setCollege("SKCET");

		Transaction tx = session.beginTransaction();
		session.save(std);
		tx.commit();
		System.out.println("Object saved successfully.....!!");
		session.close();
		sf.close();
	}
}

 
In the article Steps to be followed to use Hibernate in Java, I have explained the configuration/code used in above program in detail.
 
Now once our project is ready. Right click to project or right click to HibernateUtil.java and click Run As–>Java Application. Since I have set show_sqlto truein hibernate.cfg.xml, so the hibernate create and insert quires will be displayed on eclipse console as below.
 
Hibernate Console
 
You will see the data stored in Student table in the database.
 
Hibernate Result
 
In my next article I have implemented Select Query in Hibernate
 
download

Read More