Home Struts Training Day1 CRUD application in hibernate annotation
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

CRUD application in hibernate annotation

Advertisement
CRUD application in hibernate annotation

CRUD application in hibernate annotation

     

In this section, you will learn how to develop a CRUD application using hibernate annotation. 

Table name: student

CREATE TABLE `student` ( 
`id` int(11) NOT NULL auto_increment, 
`sname` varchar(40) NOT NULL, 
`sroll` int(11) NOT NULL, 
`scourse` varchar(10) NOT NULL, 
PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 

Follows the following steps for developing the CRUD application in hibernate annotation.

Step 1:- Creating Utility Class :- The following is the code given for the utility class for sessionFactory:

package roseindia;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
  private static final SessionFactory sessionFactory;
  static{
  try{
  sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
  }catch(Throwable th){
  System.err.println("Enitial SessionFactory creation failed"+th);
  throw new ExceptionInInitializerError(th);
  }
  }
  public static SessionFactory getSessionFactory(){
  return sessionFactory;
  } }

If you see the only change in the file for the annotations is we use AnnotationConfiguration() class instead of the Configuration() class to build the sessionFactory for the hibernate.

Step 2:

The hibernate.cfg.xml is the configuration file for the datasource in the Hibernate. This configuration file contains 

(a.) database connection setting (database driver (com.mysql.jdbc.Driver), url (jdbc:mysql://192.168.10.83/hibernateannotation), username (deepak) and password (deepak)), 

(b.) SQL dialect (dialect - org.hibernate.dialect.MySQLDialect), 

(c.) enable hibernate's automatic session context management (current_session_context_class - thread), 

(d.) disable the second level cache (cache.provider_class - org.hibernate.cache.NoCacheProvider), 

(e.) print all executed SQL to stdout (show_sql - true) and 

(f.) drop and re-create the database schema on startup (hbm2ddl.auto - none). 

The following is the example for the configuration file.

<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.83/hibernateannotation</property>
<property name="connection.username">deepak</property>
<property name="connection.password">deepak</property>
<!-- JDBC connection pool (use the built-in-->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">none</property>

<mapping class="roseindia.Student"/>

</session-factory>
</hibernate-configuration>

Now specify the class that is mapping with your database.

<mapping class="roseindia.Student"/>

Note:- Using annotations does not mean that you cannot give the hbm.xml file mappng. You can mix annotations and hbm.xml files mapping for different Pojo but you cannot mix the mappings for the same Pojo in both ways.

Step 3:

The following is the code for the Employee POJO.

/**
 
 */
package roseindia;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import javax.persistence.Table;;

/**
 @author Vinod Kumar
 *
 */
@Entity
@Table(name = "student")
public class Student implements Serializable{
  
  
  @Id
  @GeneratedValue
  private int id;
  public int getId() {
  return id;
  }

  public void setId(int id) {
  this.id = id;
  }
  
  @Column(name="sname", nullable=false,length=40)
  private String sname;
  public String getSname() {
  return sname;
  }

  public void setSname(String sname) {
  this.sname = sname;
  }
  
  @Column(name="sroll",nullable=false)
  private int sroll;
  public int getSroll() {
  return sroll;
  }

  public void setSroll(int sroll) {
  this.sroll = sroll;
  }
  
  @Column(name="scourse",nullable=false,length=10)
  private String scourse;
  public String getScourse() {
  return scourse;
  }

  public void setScourse(String scourse) {
  this.scourse = scourse;
  }
  
}

In the EJB word the entities represent the persistence object. This can be achieved by @Entity at the class level. @Table(name = "student") annotation tells the entity is mapped with the table student in the database. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance. The @Id element defines the mapping from that property to the primary key column. @Column is used to map the entities with the column in the database.

Step 4:

The following code demonstrate storing the entity in the database. The code is identical as you have used in the CRUD Hibernate applications.

CreateData.java

package roseindia;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class CreateData {

  /**
 @param args
 @throws SystemException 
 @throws HeuristicRollbackException 
 @throws HeuristicMixedException 
 @throws RollbackException 
 @throws IllegalStateException 
 @throws SecurityException 
 */
  public static void main(String[] argsthrows Exception {
  // TODO Auto-generated method stub
  
  SessionFactory sessFact = HibernateUtil.getSessionFactory();
  Session sess = sessFact.getCurrentSession();
  org.hibernate.Transaction tr = sess.beginTransaction();
  Student stu = new Student();
  stu.setSname("Vinod");
  stu.setSroll(100);
  stu.setScourse("B.C.A.");
  sess.save(stu);
  tr.commit();
  System.out.println("Successfully inserted");
  sessFact.close();
  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).

log4j:WARN Please initialize the log4j system properly.

Hibernate: insert into student (scourse, sname, sroll) values (?, ?, ?)

Successfully inserted

 

Database Table: student

Step 5:

The following code is for reading the data from database. The code is identical as you have used in above example.

ReadData.java

/**
 
 */
package roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 @author Administrator
 *
 */
public class ReadData {

  /**
 @param args
 */
  public static void main(String[] argsthrows Exception {
  // TODO Auto-generated method stub
  SessionFactory sessFact = HibernateUtil.getSessionFactory();
  Session sess = sessFact.getCurrentSession();
  Transaction tr = sess.beginTransaction();
  Query query = sess.createQuery("from Student");
  List result = query.list()
  Iterator it = result.iterator();
  System.out.println("id  sname  sroll  scourse");
  while(it.hasNext()){
  Student st = (Student)it.next();
  System.out.print(st.getId());
  System.out.print(" "+st.getSname());
  System.out.print(" "+st.getSroll());
  System.out.print(" "+st.getScourse());
  System.out.println();
  }
  sessFact.close();

  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select student0_.id as id0_, student0_.scourse as scourse0_, student0_.sname as sname0_, student0_.sroll as sroll0_ from student student0_

id sname sroll scourse

3 Amar 101 M.C.A.

4 Ravi 102 P.G.D.C.A.

5 Vinod 103 M.C.A.

6 Vinod 100 B.C.A.

 

Step 6

The following code is for updating the data into the database table "student".

UpdateData.java

/**
 
 */
package roseindia;

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

/**
 @author Administrator
 *
 */
public class UpdateData {

  /**
 @param args
 */
  public static void main(String[] argsthrows Exception{
  // TODO Auto-generated method stub
  
  SessionFactory sessFact = HibernateUtil.getSessionFactory();
  Session sess = sessFact.getCurrentSession();
  Transaction tr = sess.beginTransaction();
  Student st = (Student)sess.load(Student.class,6);
  st.setSname("Aman");
  tr.commit();
  System.out.println("Update Successfully");
  sessFact.close();

  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select student0_.id as id0_0_, student0_.scourse as scourse0_0_, student0_.sname as sname0_0_, student0_.sroll as sroll0_0_ from student student0_ where student0_.id=?

Hibernate: update student set scourse=?, sname=?, sroll=? where id=?

Update Successfully

 

Step 6: 

The following code is for deleting the data from database table "student".

DeleteData.java

/**
 
 */
package roseindia;

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

/**
 @author Administrator
 *
 */
public class DeleteData {

  /**
 @param args
 */
  public static void main(String[] argsthrows Exception{
  // TODO Auto-generated method stub
  
  SessionFactory sessFact = HibernateUtil.getSessionFactory();
  Session sess = sessFact.getCurrentSession();
  Transaction tr = sess.beginTransaction();
  Student st = (Student)sess.load(Student.class,1);
  sess.delete(st);
  System.out.println("Deleted Successfully");
  tr.commit();
  sessFact.close();

  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select student0_.id as id0_0_, student0_.scourse as scourse0_0_, student0_.sname as sname0_0_, student0_.sroll as sroll0_0_ from student student0_ where student0_.id=?

Deleted Successfully

Hibernate: delete from student where id=?

 

Download the code of the application discussed here.

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 22, 2005

Ask Questions?    Discuss: CRUD application in hibernate annotation   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Sucharit Banerjee
April 2, 2011
CRUD application in hibernate annotation

Remember Session factory is singleton here, so if you close this, you cannot reuse.
DMCA.com