Hibernate is an open-source Object-Relational Mapping (ORM) framework for the Java programming language. It provides a powerful and flexible way to map Java objects to relational database tables and to interact with those tables using object-oriented programming techniques.
Hibernate makes it easier for developers to create database-driven applications by eliminating much of the need for low-level SQL programming. Instead, developers can work with high-level Java objects, and let Hibernate handle the details of mapping those objects to the database.
Hibernate has a Session interface that provides many APIs to perform operations with the database. Here are below the Session interface methods we will use to develop CRUD operations with an example.
- save(Object object) Method - save() method persists in 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 save(Object) or update(Object) 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 Save an Entity
package net.javaguides.hibernate; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import net.javaguides.hibernate.entity.Student; import net.javaguides.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(); } } }
Read a complete step by step example at Hibernate Save an Entity Example.
- Hibernate Persist an Entity Example - In this article, we will create a simple Hibernate application to demonstrate how to persist an entity into a database.
Hibernate Read an Entity
In Hibernate, an entity can be obtained from a database using the following Session methods –
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.
Session.load() → 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.
Session.byId() → This method is used to obtain a persistence object by it being a primary identifier.
Before snippets read an entity from a database using Session.get(), Session.load() and Session.byId() methods:
package net.javaguides.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.javaguides.hibernate.entity.Student;
import net.javaguides.hibernate.util.HibernateUtil;
public class StudentDao {
public void getStudent(int id) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// get Student entity using get() method
Student student = 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();
}
}
public void loadStudent(int id) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// get Student entity using load() method
Student student = 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();
}
}
public void getStudentById(int id) {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
// start a transaction
transaction = session.beginTransaction();
// Obtain an entity using byId() method
Student student = 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();
}
}
public void saveStudent(Student student) {
Transaction transaction = null;
try (Session session = 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();
}
}
}
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.
Session.load() → 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.
Session.byId() → This method is used to obtain a persistence object by it being a primary identifier.
package net.javaguides.hibernate.dao; import org.hibernate.Session; import org.hibernate.Transaction; import net.javaguides.hibernate.entity.Student; import net.javaguides.hibernate.util.HibernateUtil; public class StudentDao { public void getStudent(int id) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // get Student entity using get() method Student student = 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(); } } public void loadStudent(int id) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // get Student entity using load() method Student student = 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(); } } public void getStudentById(int id) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // Obtain an entity using byId() method Student student = 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(); } } public void saveStudent(Student student) { Transaction transaction = null; try (Session session = 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(); } } }
Read a complete step by step example at Hibernate get(), load() and byId() Method Examples.
Hibernate Update an Entity
package net.javaguides.hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import net.javaguides.hibernate.entity.Student; import net.javaguides.hibernate.util.HibernateUtil; public class App { public static void main(String[] args) { Student student = new Student("Ramesh", "Fadatare", "rameshfadatare@javaguides.com"); saveOrUpdateStudent(student); } public static void saveOrUpdateStudent(Student student) { Transaction transaction = null; try (Session session = 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(); } } }
Read a complete step by step example at Hibernate 5 - saveOrUpdate() Method Example.
Hibernate Delete or Remove an Entity
The following snippets or examples demonstrate the use of Session.delete() and Session.remove() methods.
Session.delete(Object object) Method
EntityManager.remove(Object entity)
package net.javaguides.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.javaguides.hibernate.entity.Student;
import net.javaguides.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();
}
}
}
package net.javaguides.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.javaguides.hibernate.entity.Student;
import net.javaguides.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();
}
}
}
Read a complete step by step example at Hibernate 5 - Delete or Remove an Entity Example.
Comments
Post a Comment
Leave Comment