Hibernate example using annotation

As we discussed a simple hibernate program to save a student class object into the database using xml mapping. Let us do the same exercise with the annotations.

Example:

Student.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
 
/**
 * This class represents a persistent class for Student.
 * @author javawithease
 */
@Entity  
@Table(name= "STUDENT")  
public class Student {
	//data members
	private int studentId;
	private String firstName;
	private String lastName;
	private String className;
	private String rollNo;
	private int age;
 
	//no-argument constructor
	public Student(){
 
	}
 
	//getter and setter methods
	@Id
	@GeneratedValue
	@Column(name = "Student_Id", unique = true, nullable = false)
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
 
	@Column(name = "First_Name")
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
 
	@Column(name = "Last_Name")
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
 
	@Column(name = "Class")
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
 
	@Column(name = "RollNo")
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
 
	@Column(name = "Age")
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
 
}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <property name="dialect">
           org.hibernate.dialect.OracleDialect
        </property>
        <property name="connection.url">
           jdbc:oracle:thin:@localhost:1521:XE
        </property>
        <property name="connection.username">
           system
        </property>
        <property name="connection.password">
           oracle
        </property>
        <property name="connection.driver_class">
           oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hbm2ddl.auto">
           update
        </property>
        <property name="show_sql">
           true
        </property>
 
        <mapping resource="student.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * This is a utility class for getting the hibernate session object.
 * @author javawithease
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
                                             buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
        try {
        	//Create the session factory object.
        	return new AnnotationConfiguration().configure()
        	.buildSessionFactory(); 
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return sessionFactory;
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
}

HibernateTest.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.javawithease.persistence.HibernateUtil;
 
/**
 * This class is used for the hibernate operations.
 * @author javawithease
 */
public class HibernateTest {
	public static void main(String args[]){
	//Create the student object.
	Student student = new Student();
 
	//Setting the object properties.
	student.setFirstName("Vivek");
	student.setLastName("Solenki");
	student.setClassName("MCA final");
	student.setRollNo("MCA/07/70");
	student.setAge(27);
 
	Transaction tx = null;
	//Get the session object.
	Session session = 
                      HibernateUtil.getSessionFactory().openSession();
	try{
              //Start hibernate session.
	      tx = session.beginTransaction();
 
              //Insert a new student record in the database.
	      session.save(student); 
 
              //Commit hibernate transaction if no exception occurs.
	      tx.commit();
              System.out.println("Saved Successfully.");
	  }catch (HibernateException e) {
	     if(tx!=null){
                 //Roll back if any exception occurs. 
	         tx.rollback();
	     }
	     e.printStackTrace(); 
	  }finally {
             //Close hibernate session.
	     session.close(); 
	  }
	}
}

Output:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, Class, 
RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Saved Successfully.

Download this example.
 
Next Topic: Hibernate collections mappings with example.
Previous Topic: Hibernate example using xml mapping.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.