
Quick Contact
Java Tutorial
- What is Java?
- History of Java
- Hello Java Program
- Features of Java
- Basic Syntax
- Java Setup
- Data Types in Java
- Java Variables
- Operators in Java
- JVM
- Java If-else Statement
- Switch Case Statement
- Java Loops
- Do-While Loop
- Java While Loop
- Continue Statement
- Break Statement in Java
- Constructors in Java
- Oops Concept in Java
- Features of OOPs
- Inheritance
- Exeception handeling
- Aggregation (HAS-A relationship) in Java
- Method Overriding in Java
- Method Overloading
- Java Static Keyword
- Java This Keyword
- Java Final Keyword
- Polymorphism
- Static Binding and Dynamic Binding
- Abstract class in Java
- Access Modifiers in Java
- Difference between abstract class and interface
- Interface in Java
- Garbage Collection in Java
- Java Package
- Encapsulation
- Serialization and Deserialization in Java
- Java Inner Classes
- Java Applets
- Multithreading in Java
- Thread Priorities in Java
- Thread Creation
- Inter Thread Communication
- Wrapper Classes in Java
- Java Input Output
- Java AWT Introduction
- Java Layout Manager
- Java Layout Policy
- Java AWT Events
- Collection Framework
- Collection Framework List Interface
- Swing in Java
- Swing Utility Classes
- Swing Layout Managers
- Java JDBC
- Hibernate Framework Overview – Architecture and Basics
Springboot
- Spring Environment Setup
- Spring Boot CRUD REST API Project using IntelliJ IDEA | Postman | MySQL
- Dockerizing Spring Boot Application | Spring Boot Docker Tutorial
- spring-boot-restapidocumentation with swagger
- Spring Boot HttpClient Overview
- Apache HttpClient POST HTTP Request Example
- Apache HttpClient PUT HTTP Request Example
- Apache HttpClient DELETE HTTP Request Example
- Apache HttpClient HTML Form POST Request Example
- Spring Boot JSP Exampl
- Deploying Spring Boot WAR file with JSP to Tomcat
- Spring Boot Annotations
- Spring Core Annotations
- Spring MVC Annotations with Examples
- Spring Scheduling Annotations
- Spring - Java-based Container Configuration
- Spring Java Based Configuration Example
Hibernate
- Hibernate 5 hello world
- Hibernate- One to One Unidirectional Mapping Annotation Example
- Hibernate - Batch Processing
- Hibernate - Interceptors
- Hibernate 5 - Create, Read, Update and Delete (CRUD) Operations Example
- Hibernate Transaction Management
- Hibernate One to Many Unidirectional Mapping Example
- Hibernate One to Many Bidirectional Mapping Example
- Hibernate Many to Many Annotation Mapping Example
- Hibernate Primary KeyJoin Column
- Hibernate First Level Cache with Example
- Hibernate XML Configuration Example with Maven + Eclipse + MySQL Database
- Hibernate Java Configuration Example
- JPA 2 with Hibernate 5 Bootstrapping Example
- JPA and Hibernate Cascade Types
- Hibernate/JPA - Primary Key Generation
- Hibernate 5 - Enum Type Mapping Example
- Hibernate Component Mapping
- Hibernate Object States – Transient,Persistent and Detached
- Hibernate 5 - Save an Entity Example
- Hibernate 5 - Persist an Entity Example
- Hibernate 5 - saveOrUpdate() Method Example
- Hibernate 5 - get(), load() and byId() Method Examples
- Hibernate 5 - merge() Example
- Hibernate 5 - Delete or Remove an Entity Example
- Hibernate 5 - load() Method Example
- Hibernate Session Interface Methods
- Hibernate Session.clear() Method Example
- Introduction Of Java strutes to Architecture
- Struts 2 - Architecture
- Struts 2 - Configuration Files
- Struts 2 - Actions
- Struts 2 - Interceptors
- Struts 2 - Results & Result Types
- Struts 2 - Value Stack/OGNL
- Struts 2 - File Uploading
- Struts 2 - Database Access
- Struts 2 - Validations Framework
JAVA FX
- JavaFX Tutorial
- Introduction to JavaFX Pane
- JavaFX Popup
- JavaFX group
- JavaFX Controller
- JavaFX Gradient Color
- JavaFXAnchorPane
- JavaFXTabPane
- JavaFX Scene
- JavaFX Stage
- JavaFXWebView
- JavaFX Timeline
- JavaFX Timer
- JavaFX Image
- JavaFX Background
- JavaFX dialog
- JavaFX Font
- JavaFXTextArea
- JavaFXObservableList
- JavaFX GUI
- JavaFX FXML
- JavaFXEventHandler
- JavaFXGradle
- JavafxScrollpane
- JavaFXAPI
Hibernate 5 – Create, Read, Update and Delete (CRUD) Operations Example
Hibernate is a Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides a reference implementation of the Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling.
CRUD operations are Create(save), Read(select), Update(update) and Delete(delete). Hibernate has Session interface which provides many APIs to perform operations with database.
Here are below Session interface methods we will use to develop CRUD operations with an example.
save(Object object) Method
save() method persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade=”save-update”.
saveOrUpdate(Object object) Method
This method either <strong>save(Object)</strong> or <i>update(Object)</i> the given instance, depending upon the resolution of the unsaved-value checks (see the manual for a discussion of unsaved-value checking).
Session.delete(Object object) Method
Remove a persistent instance from the datastore.
Session.get()
This method returns a persistence object of the given class with the given identifier. It will return null if there is no persistence object.
Hibernate 5 – Save an Entity
Let’s demonstrate how to save an entity into a database using Hibernate Session.save() method.
packagenet.ducatindia.hibernate;
importjava.util.List;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
importnet.ducatindia.hibernate.entity.Student;
importnet.ducatindia.hibernate.util.HibernateUtil;
public class App {
public static void main(String[] args) {
Student student = new Student(“Ramesh”, “Fadatare”, “rameshfadatare@javaguides.com”);
Student student1 = new Student(“John”, “Cena”, “john@javaguides.com”);
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// save the student objects
session.save(student);
session.save(student1);
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
List < Student > students = session.createQuery(“from Student”, Student.class).list();
students.forEach(s – >System.out.println(s.getFirstName()));
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
</pre>
<h5>Hibernate 5 – Read an Entity</h5>
<h5>Session.get() → </h5>
<p>This method returns a persistence object of the given class with the given identifier. It will return null if there is no persistence object.</p>
<h5>Session.load() → </h5>
<p>This method returns a persistence object of the given class with the given identifier. It will throw an exception ObjectNotFoundException if an entity does not exist in the database. The load() method may return a proxy object instead of a real persistence object.</p>
<h5>Session.byId() → </h5>
<p>This method is used to obtain a persistence object by it a primary identifier.</p>
<p>Before snippets to read an entity from a database </p>
<p>using Session.get(), Session.load() and Session.byId() methods:</p>
<pre>
packagenet.ducatindia.hibernate.dao;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
importnet.ducatindia.hibernate.entity.Student;
importnet.ducatindia.hibernate.util.HibernateUtil;
publicclassStudentDao {
publicvoidgetStudent(intid) {
Transactiontransaction=null;
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction=session.beginTransaction();
// get Student entity using get() method
Studentstudent=session.get(Student.class, id);
System.out.println(student.getFirstName());
System.out.println(student.getEmail());
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction !=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
publicvoidloadStudent(intid) {
Transactiontransaction=null;
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction=session.beginTransaction();
// get Student entity using load() method
Studentstudent=session.load(Student.class, id);
System.out.println(student.getFirstName());
System.out.println(student.getEmail());
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction !=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
publicvoidgetStudentById(intid) {
Transactiontransaction=null;
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction=session.beginTransaction();
// Obtain an entity using byId() method
Studentstudent=session.byId(Student.class).getReference(id);
System.out.println(student.getFirstName());
System.out.println(student.getEmail());
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction !=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
publicvoidsaveStudent(Studentstudent) {
Transactiontransaction=null;
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction=session.beginTransaction();
// save the student object
session.save(student);
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction !=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
</pre>
<h5>Hibernate 5 – Update an Entity</h5>
<p>Let’s write a code to demonstrate how to save or update an entity in the database using the saveOrUpdate() method. </p>
<pre>
packagenet.ducatindia.hibernate;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
importnet.ducatindia.hibernate.entity.Student;
importnet.ducatindia.hibernate.util.HibernateUtil;
publicclassApp {
publicstaticvoidmain(String[] args) {
Studentstudent=newStudent(“Anoop”, “Arun”, “Anoop@ducat.com”);
saveOrUpdateStudent(student);
}
publicstaticvoidsaveOrUpdateStudent(Studentstudent) {
Transactiontransaction=null;
try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction=session.beginTransaction();
// save the student object
session.saveOrUpdate(student);
// get entity from database
Student student2 =session.get(Student.class, 1);
// do changes
student2.setFirstName(“Ram”);
// update the student object
session.saveOrUpdate(student2);
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction !=null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
</pre>
<h5>Hibernate 5 – Delete or Remove an Entity</h5>
<p>In Hibernate, an entity can be removed from a database by calling the <i>Session.delete()</i> or <i>Session.remove()</i>. Using these methods, we can remove a transient or persistent object from datastore.</p>
<pre>
packagenet.ducatindia.hibernate.dao;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
importnet.ducatindia.hibernate.entity.Student;
import net.ducatindia.hibernate.util.HibernateUtil;
public class SessionDeleteExample {
public void deleteStudent(int id) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// Delete a persistent object
Student student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println(“student 1 is deleted”);
}
// Delete a transient object
Student student2 = new Student();
student2.setId(2);
session.delete(student2);
System.out.println(“Student 2 is deleted”);
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
The following example snippet deletes transient and persistent objects from datastore using Session.remove() method.
packagenet.ducatindia.hibernate.dao;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
import net.ducatindia.hibernate.entity.Student;
import net.ducatindia.hibernate.util.HibernateUtil;
public class SessionRemoveExample {
public void removeStudent(int id) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// Delete a persistent object
Student student = session.get(Student.class, id);
if (student != null) {
session.remove(student);
System.out.println(“student 1 is deleted”);
}
// Delete a transient object
Student student2 = new Student();
student2.setId(2);
session.remove(student2);
System.out.println(“Student 2 is deleted”);
// commit transaction
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
}
}
Apply now for Advanced Java Training Course