CRUD Operations Using Hibernate 5 & Oracle
Hibernate is Java based ORM tool that provides a framework for
mapping application domain objects to the relational database tables and
vice versa. It provides reference implementation of Java Persistence
API, that makes it a great choice as an ORM tool with benefits of loose
coupling
Framework provides option to map plain old Java objects
to traditional database tables with the use of JPA annotations as well
as XML based configuration.
A CRUD operation deals
with creating, retrieving, updating, and deleting records from the
table. In this tutorial we will see how it is done using Hibernate
annotations. We are going to discuss 4 main functionalities:
- Create a record
- Read a record
- Update a Record
- Delete a Record
CREATE TABLE student
( id number(11) NOT NULL,
first_name varchar2(50)
default null,
last_name varchar2(50)
default null,
email varchar2(50) default
null,
CONSTRAINT student_pk PRIMARY
KEY (id)
);
//To create Id as auto increment,we need to sequence & trigger
CREATE SEQUENCE student_seq START WITH 1;
CREATE OR REPLACE TRIGGER student_bir
BEFORE INSERT ON student
FOR EACH ROW
BEGIN
SELECT student_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/
select * from student;
|
| Annotation | Modifier | Description |
@Entity | Marks a class as a Hibernate Entity (Mapped class) | |
@Table | Name | Maps this class with a database table specified by name modifier. If the name is not supplied it maps the class with a table having the same name as the class. |
@Id | Marks this class field as a primary key column. | |
@GeneratedValue | Instructs database to generate a value for this field automatically. | |
@Column | Name | Maps this field with table column specified by name and uses the field name if name modifier is absent. |
Project Creation
create a Java based Maven project with Eclipse
SessionFactory
- Reads the hibernate config file
- Creates Session objects
- Heavy-weight object
- Only create once in your app
Session
- Wraps a JDBC connection
- Main object used to save/retrieve object
- short-lived object
- Retrived from SessionFactory
Maven Dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Hibernate</groupId>
<artifactId>HibernateDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HibernateDemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--
https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
</project>
|
Create a record
Hibernate 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>
<!-- <property
name="hbm2ddl.auto">update</property> -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</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="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread </property>
<!-- <mapping resource="EMP.hbm.xml"/>
-->
</session-factory>
</hibernate-configuration>
|
ID Generation Strategies
GenerationType.AUTO = Pick an appropriate strategy for the particular database
GenerationType.IDENTITY = Assign primary keys using a database identity column
GenerationType.SEQUENCE = Assign primary keys using a database sequence
GenerationType.TABLE = Assign primary keys using an underlying
database table to ensure uniqueness
Implementation of Model Class
package com.hibernate.entity;
import
javax.persistence.Column;
import
javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student {
@Id
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstname;
@Column(name = "last_name")
private String lastname;
@Column(name = "email")
private String email;
public Student(String firstname, String lastname, String email) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student [id=" + id + ",
firstname=" + firstname + ", lastname=" + lastname + ", email=" + email + "]";
}
}
|
Implementation of DAO Class
package Hibernate.HibernateDemo;
import org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.Transaction;
import
org.hibernate.cfg.Configuration;
import
com.hibernate.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
// create session factory
SessionFactory
factory = new
Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
// create a student object
Student tempstu = new Student("Devyan", "Thakur", "devyan@newton.com");
/*
* // save student object session.save(tempstu);
*
*
* //commit transaction
session.getTransaction().commit();
*
* System.out.println("Done!");
*/
// creating transaction object
Transaction t = session.beginTransaction();
// persisting the object
session.persist(tempstu);
// commit transaction
t.commit();
session.close();
factory.close();
System.out.println("successfully saved");
}
}
|
INFO: HHH000182: No default (no-argument) constructor for class:
com.hibernate.entity.Student (class must be instantiated by Interceptor)
Hibernate: insert into student (email, first_name, last_name,
id) values (?, ?, ?, ?)
successfully saved
Read a record
package Hibernate.HibernateDemo;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.
import org.hibernate.Session;
import
org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.cfg.Configuration;
import
com.hibernate.entity.Student;
public class ReadStudentdemo {
static Session session;
static SessionFactory sessionFactoryObj;
public static List<Student>
displayRecords() {
List studentsList = new ArrayList();
// create session factory
SessionFactory factory = new
Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
// create session
session = factory.getCurrentSession();
// Getting Transaction Object From Session Object
session.beginTransaction();
studentsList = session.createQuery("FROM Student").list();
session.close();
factory.close();
System.out.println("successfully Retrived");
return studentsList;
}
public static void main(String[] args) {
List<Student>
viewstudent = ReadStudentdemo.displayRecords();
for (Student s : viewstudent) {
System.out.println("Student id:" + s.getId() + "Student Name:" + s.getFirstname());
}
}
}
|
Output:
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]
successfully Retrived
Student id:1Student Name:Paul
Student id:2Student Name:Devyan
Student id:7Student Name:Rahul
Output:
If I can be of assistance, please do not hesitate to contact me:)
successfully Retrived
Student id:1Student Name:Paul
Student id:2Student Name:Devyan
Student id:7Student Name:Rahul
Update a Record
package Hibernate.HibernateDemo;
import org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.cfg.Configuration;
import
com.hibernate.entity.Student;
public class UpdateStudentRecord {
static Session session;
static SessionFactory sessionFactoryObj;
public static void updateStudent(int student_id) {
// create session factory
SessionFactory factory = new
Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
// create session
session = factory.getCurrentSession();
// Getting Transaction Object From Session Object
session.beginTransaction();
//Creating Transaction Entity
Student stu=session.get(Student.class, student_id);
stu.setFirstname("Harendera");
//committing the transaction to the database
session.getTransaction().commit();
session.close();
factory.close();
}
public static void main(String[] args) {
int updateId=1;
UpdateStudentRecord.updateStudent(updateId);
}
}
|
Output:
INFO: HHH000400: Using dialect:
org.hibernate.dialect.Oracle10gDialect
Hibernate: select student0_.id as id1_0_0_, student0_.email as
email2_0_0_, student0_.first_name as first_name3_0_0_, student0_.last_name as
last_name4_0_0_ from student student0_ where student0_.id=?
Hibernate: update student set email=?, first_name=?, last_name=?
where id=?
Oct 30, 2018 9:24:49 AM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:oracle:thin:@localhost:1521:xe]
|
Delete a Record
package Hibernate.HibernateDemo;
import org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.cfg.Configuration;
import
com.hibernate.entity.Student;
public class DeleteStudentRecord {
static Session session;
static SessionFactory sessionFactoryObj;
public static void deleteStudent(int student_id) {
// create session factory
SessionFactory factory = new
Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
// create session
session = factory.getCurrentSession();
// Getting Transaction Object From Session Object
session.beginTransaction();
// Creating Transaction Entity
Student stu = session.get(Student.class, student_id);
session.delete(stu);
// committing the transaction to the database
session.getTransaction().commit();
session.close();
factory.close();
}
public static void main(String[] args) {
int id=1;
DeleteStudentRecord.deleteStudent(id);
}
}
|
INFO: HHH000400: Using dialect:
org.hibernate.dialect.Oracle10gDialect
Hibernate: select student0_.id as id1_0_0_, student0_.email as
email2_0_0_, student0_.first_name as first_name3_0_0_, student0_.last_name as
last_name4_0_0_ from student student0_ where student0_.id=?
Hibernate: delete from student where id=?
Oct 30, 2018 10:41:52 AM
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl
stop
INFO: HHH10001008: Cleaning up connection pool
[jdbc:oracle:thin:@localhost:1521:xe]
|
If I can be of assistance, please do not hesitate to contact me:)



0 comments:
Post a Comment