Quick Contact

    Hibernate

    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

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.