CRUD application in JPA

In this section, we are going to learn how to develop a CRUD application in JPA (Java Persistence APIs).

CRUD application in JPA

CRUD application in JPA

     

In this section, we are going to learn how to develop a CRUD application in JPA (Java Persistence APIs). 

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 JPA :

Step 1:

The hibernate.cfg.xml is the configuration file for the datasource in JPA. 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="src.roseindia.Student"/>

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

Now specify the class that is mapping with your database.

<mapping class="src.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 2:

The following is the code for the Student 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 (hibernateannotation). 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 3:

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

createData.java

/**
 * 
 */
package src.roseindia;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

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

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

  /**
   * @param args
   */

  public static void main(String[] args) throws Exception{
    // TODO Auto-generated method stub

    SessionFactory sessFact = new AnnotationConfiguration().configure().buildSessionFactory();
      Session sess = sessFact.openSession();
      Transaction tr = sess.beginTransaction();
      Student stu = new Student();
      stu.setSname("Amardeep Patel");
      stu.setSroll(150);
      stu.setScourse("M.C.A.");
      sess.persist(stu);
      tr.commit();
      sess.close();
      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 4:

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

readData.java /**
 * 
 */
package src.roseindia;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

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

  /**
 * @param args
 */
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  AnnotationConfiguration config = new AnnotationConfiguration();
  config.addAnnotatedClass(Student.class);
  SessionFactory sessFact = config.configure().buildSessionFactory();
  Session sess = sessFact.getCurrentSession();
  sess.beginTransaction();
  Query queryResult = sess.createQuery("from Student");
  List userList = queryResult.list();
  Iterator it = userList.iterator();
  while(it.hasNext()){
  Student stu = (Student)it.next();
  System.out.print(stu.getSname()+" ");
  System.out.print(stu.getSroll()+" ");
  System.out.print(stu.getScourse());
  System.out.println();
  }
  }

}

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_
Vinod 103 M.C.A.
Aman 100 B.C.A.
Amar 150 M.C.A.
Amardeep Patel 150 M.C.A.


Step 6

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

updateData.java

/**
 * 
 */
package src.roseindia;

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

import src.roseindia.Student;

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

  /**
 * @param args
 */
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  AnnotationConfiguration config = new AnnotationConfiguration();
  config.addAnnotatedClass(Student.class);
  SessionFactory sessFact = config.configure().buildSessionFactory();
  Session sess = sessFact.getCurrentSession();
  Transaction tr = sess.beginTransaction();
  Student st = (Student)sess.load(Student.class,8);
  st.setSname("Suman");
  System.out.println("Successfully Updated");
  tr.commit();
  sessFact.close();
  
  
  }

}

Output:

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=? Successfully Updated
Hibernate: update student set scourse=?, sname=?, sroll=? where id=?
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.


Step 6:  1

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

deleteData.java

/**
 * 
 */
package src.roseindia;

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


import src.roseindia.Student;

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

  /**
 * @param args
 */
  public static void main(String[] args) {
  // TODO Auto-generated method stub

  AnnotationConfiguration config = new AnnotationConfiguration();
  config.addAnnotatedClass(Student.class);
  SessionFactory sessFact = config.configure().buildSessionFactory();
  Session sess = sessFact.getCurrentSession();
  Transaction tr = sess.beginTransaction();
  Student st = (Student)sess.load(Student.class,10);
  sess.delete(st);
  tr.commit();
  System.out.println("Update Successfully");
  sessFact.close();
  }

}

Output: 2

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: delete from student where id=?
Deleted Successfully


Download the code of the application discussed here.