Hibernate CRUD operations with auto increment in Oracle SQL with examples

Previously I was explained Hibernate CRUD Operations without Auto Increment column. Here I am explaining how to do Hibernate CRUD operations with Primary key column as auto increment in Oracle SQL with examples. There will be slight difference in pseudo code compare to the previous example. But, mostly the same classes I have used to maintain the consistency.

Before going to write the java logic, we have small work to do in the database to create the table and sequence. Please execute the below lines of SQL script in your SQL prompt or SQL developer.

To create the table with primary key:
create table USER_INFO(user_id NUMBER,user_name VARCHAR2(50),password VARCHAR2(50),CONSTRAINT user_id_pk PRIMARY KEY(user_id));

To alter the Primary Key Constraint:
alter table USER_INFO ADD CONSTRAINT user_id_pk primary key(user_id);

To create the sequence:
create sequence user_sequence start with 1 increment by 1 nomaxvalue;

That's it we are done with our work in database side. Now, we will proceed to write our Java/Hibernate logic.

Project Structure:

Required Libraries:

We need to configure the Database by using the hibernate.cfg.xml file. Since, my database located in another system, I am not using the localhost. If you have database in your system, you may change the configuration as per your requirement.

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="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@vserver12:1521:TRADE</property>
  <property name="hibernate.connection.username">jtb</property>
  <property name="hibernate.connection.password">jtb</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">JTB</property>
  <property name="show_sql">true</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
  <mapping class="com.hibernate.aiexample.model.User" />
 </session-factory>
</hibernate-configuration>

Here is the bean class which I am using annotations to configure with database table.

User.java:
package com.hibernate.aiexample.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "USER_INFO")
public class User implements Serializable {

 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence")
 @SequenceGenerator(name = "user_sequence", sequenceName = "user_sequence", allocationSize = 1, initialValue = 1)
 @Column(name = "USER_ID")
 private long userId;
 @Column(name = "USER_NAME")
 private String userName;
 @Column(name = "PASSWORD")
 private String password;

 public long getUserId() {
  return userId;
 }

 public void setUserId(long userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 @Override
 public String toString() {
  return "User [userId=" + userId + ", userName=" + userName
    + ", password=" + password + "]";
 }

 public User(long userId, String userName, String password) {
  super();
  this.userId = userId;
  this.userName = userName;
  this.password = password;
 }

 public User() {

 }

}

In the above User.java, I have applied various annotations tags to userId property.

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence")
@SequenceGenerator(name = "user_sequence", sequenceName = "user_sequence", allocationSize = 1, initialValue = 1)

The above @Id will be use to refer the Primary Key column in the table. and @GenerateValue tag used to refer Primary key value generation type like assigned, increment or native, etc.. In the above example, I am using sequence which I have created in the database with the name as user_serquence. Since, I am using sequence to generate the primary key value I am using @SequenceGenerator tag.

Instead of calling SessionFactory creation login in multiple time in multiple classes, I have written SessionFactory creation logic into the separate class and using the single method to get instance of the SessionFactory or Session interfaces.

HibernateUtil.java
package com.hibernate.aiexample.util;

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

public class HibernateUtil {

 private static SessionFactory sf = null;

 private static synchronized SessionFactory getSessionFactoryInstance() {
  if (sf == null) {
   sf = new Configuration().configure().buildSessionFactory();
  }
  return sf;
 }

 public static Session getSessionInstance() {
  return getSessionFactoryInstance().openSession();
 }

 public static void closeSession(Session session) {
  if (session != null) {
   session.close();
  }
 }

}

Once initial setup is done, we will move to write the logic for CRUD operations.

CreateUser.java
package com.hibernate.aiexample.test;

import org.hibernate.Session;

import com.hibernate.aiexample.model.User;
import com.hibernate.aiexample.util.HibernateUtil;

public class CreateUser {

 public static void main(String[] args) {
  // Getting Session instance by calling getSessionInstace() method in
  // HibernateUtil.java
  Session session = HibernateUtil.getSessionInstance();
  // Beginning the Transaction
  session.beginTransaction();
  // Creating the User object and setting the values
  User user = new User();
  user.setUserName("Subbareddy");
  user.setPassword("Nallamachu");
  // Persisting the user object into the database table
  session.save(user);
  // Committing the values into the database table
  session.getTransaction().commit();
 }

}

Once you execute the above class, you will see the insertion script which executed by hibernate like below.
Hibernate: select JTB.user_sequence.nextval from dual
Hibernate: insert into JTB.USER_INFO (PASSWORD, USER_NAME, USER_ID) values (?, ?, ?)

RetrieveUser.java:
package com.hibernate.aiexample.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;

import com.hibernate.aiexample.model.User;
import com.hibernate.aiexample.util.HibernateUtil;

public class RetrieveUser {
 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionInstance();
  session.beginTransaction();
  Criteria ctr = session.createCriteria(User.class);
  List<User> userList = ctr.list();
  if (userList.size() > 0 && userList != null) {
   for (User user : userList) {
    System.out.println("User Id: " + user.getUserId());
    System.out.println("User Name: " + user.getUserName());
    System.out.println("Password: " + user.getPassword());
    if (userList.size() > 1) {
     System.out.println();
    }
   }
  }
 }
}

Once successfully execute the above class you can see the results in console like,

Hibernate: select this_.USER_ID as USER_ID1_0_0_, this_.PASSWORD as PASSWORD2_0_0_, this_.USER_NAME as USER_NAME3_0_0_ from JTB.USER_INFO this_
User Id: 1
User Name: Subbareddy
Password: Nallamachu

UpdateUser.java:
package com.hibernate.aiexample.test;

import org.hibernate.Session;

import com.hibernate.aiexample.model.User;
import com.hibernate.aiexample.util.HibernateUtil;

public class UpdateUser {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionInstance();
  session.beginTransaction();
  User user = (User) session.createQuery("from User").list().get(0);

  if (user != null) {
   user.setUserName("JavaTbrains");
   session.update(user);
   session.getTransaction().commit();
  }
 }

}

Once you execute the above class, you will see the query which is executed by hibernate in console like,
Hibernate: select user0_.USER_ID as USER_ID1_0_, user0_.PASSWORD as PASSWORD2_0_, user0_.USER_NAME as USER_NAME3_0_ from JTB.USER_INFO user0_
Hibernate: update JTB.USER_INFO set PASSWORD=?, USER_NAME=? where USER_ID=?

Note: To know the record get's updated or not, execute again the RetrieveUser.java. You can see the updated result.

Finally to delete the user record from the database table, execute the below DeleteUser.java file...
DeleteUser.java:
package com.hibernate.aiexample.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;

import com.hibernate.aiexample.model.User;
import com.hibernate.aiexample.util.HibernateUtil;

public class DeleteUser {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionInstance();
  session.beginTransaction();
  Criteria ctr = session.createCriteria(User.class);
  User user = (User) ctr.uniqueResult();
  String qryStr = "delete USER_INFO where user_id="+user.getUserId();
  Query query = session.createSQLQuery(qryStr);
  int noOfRecords = query.executeUpdate();
  if (noOfRecords > 0) {
   System.out.println(noOfRecords + " records deleted from table.");
  }
  session.getTransaction().commit();
 }

}

Once, you execute the above class you will see the results in your console like,
Hibernate: select this_.USER_ID as USER_ID1_0_0_, this_.PASSWORD as PASSWORD2_0_0_, this_.USER_NAME as USER_NAME3_0_0_ from JTB.USER_INFO this_
Hibernate: delete USER_INFO where user_id=2
1 records deleted from table.

Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example