Skip to main content

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

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...