Step 6 – 11 Methods of hibernate

1- get() method

2- load() method,

3- save() method

4- saveOrUpdate() method

5- update() method

6- persist() method

7- merge() method

8- delete() method

9- remove() method

10- evict() method

11- clear() method

We are going to create single simple program to demonstrate all them, one by one.

First, we will configure everything which will be needed-


1- Class (which need to be saved/updated/deleted and retrieved.
2- Hibernate Configuration file
3- Hibernate Mapping File

4- Create the Hibernate SessionFactory object
5- Open a Hibernate session

1- Class, we going to use for all above operations is below-

import java.util.Date;

public class Person {
 
    private long id;
    private String name;
    private Date dob;
 
    public Person() {
    }
 
    public Person(String name, Date dob) {
        this.name = name;
        this.dob = dob;
    }
 
    // getters and setters
 
    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Date getDob() {
        return dob;
    }
 
    public void setDob(Date dob) {
        this.dob = dob;
    }
 
}

2- Hibernate configuration file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <mapping resource="Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

3- Hibernate Mapping File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="Person" table="person">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" column="name"/>
        <property name="dob" column="dob"/>
    </class>
</hibernate-mapping>

4- Create the Hibernate SessionFactory object

Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();

5- Open a Hibernate session

Session session = sessionFactory.openSession();

Now the program which demonstrates all the methods above-mentioned: –

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class Main {

    public static void main(String[] args) {

        // Step 1: Set up the Hibernate configuration file
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");

        // Step 2: Define the Hibernate mapping file
        // Person.hbm.xml is already defined

        // Step 3: Create the Hibernate SessionFactory object
        SessionFactory sessionFactory = cfg.buildSessionFactory();

        // Step 4: Open a Hibernate session
        Session session = sessionFactory.openSession();

        // Step 5: Create and save a new Person object using save() method
        Person person1 = new Person();
        person1.setName("Kuldeep kaushik");
        person1.setDob(new Date());

        Transaction transaction = session.beginTransaction();
        session.save(person1);
        transaction.commit();

        // Step 6: Retrieve the Person object using get() method
        Person retrievedPerson1 = session.get(Person.class, person1.getId());
        System.out.println("Retrieved person1: " + retrievedPerson1.getName() + " (DOB: " + retrievedPerson1.getDob() + ")");

        // Step 7: Create and save another Person object using persist() method
        Person person2 = new Person();
        person2.setName("deepu sharma");
        person2.setDob(new Date());

        transaction = session.beginTransaction();
        session.persist(person2);
        transaction.commit();

        // Step 8: Update the Person object using update() method
        transaction = session.beginTransaction();
        person2.setName("somi kaushik");
        session.update(person2);
        transaction.commit();

        // Step 9: Retrieve the Person object using load() method
        Person retrievedPerson2 = session.load(Person.class, person2.getId());
        System.out.println("Retrieved person2: " + retrievedPerson2.getName() + " (DOB: " + retrievedPerson2.getDob() + ")");

        // Step 10: Save or update the Person object using saveOrUpdate() method
        Person person3 = new Person();
        person3.setName("deep sharma");
        person3.setDob(new Date());

        transaction = session.beginTransaction();
        session.saveOrUpdate(person3);
        transaction.commit();

        // Step 11: Merge the Person object using merge() method
        Person person4 = new Person();
        person4.setName("puju sharma");
        person4.setDob(new Date());

        transaction = session.beginTransaction();
        Person mergedPerson4 = (Person) session.merge(person4);
        transaction.commit();
        System.out.println("Merged person4: " + mergedPerson4.getName() + " (DOB: " + mergedPerson4.getDob() + ")");

        // Step 12: Delete the Person object using delete() method
        transaction = session.beginTransaction();
        session.delete(person1);
        transaction.commit();

        // Step 13: Remove the Person object from the session cache using evict() method
        session.evict(person2);

        // Step 14: Clear the session cache using clear() method
        session.clear();


    // Step 15: Close the Hibernate session and session factory
    session.close();
    sessionFactory.close();
}

Explanation of each method used in above program-

1- #### `get()`

The `get()` method is used to retrieve an object by its identifier (primary key). We retrieve the `person1` object by its `id` using the `get()` method in Step 6:
Person retrievedPerson1 = session.get(Person.class, person1.getId());

2- #### `load()`

The `load()` method is used to retrieve an object by its identifier (primary key) as a proxy. The object is not actually loaded until its properties are accessed. We retrieve the `person2` object by its `id` using the `load()` method in Step 9: Person retrievedPerson2 = session.load(Person.class, person2.getId());

3- #### `save()`

The `save()` method is used to save a new object to the database. We save the `person1` object using the `save()` method in Step 5: Transaction transaction = session.beginTransaction();
session.save(person1);
transaction.commit();

4- #### `persist()`

The `persist()` method is used to make a new object persistent. It does not return anything and does not guarantee when the insert will happen. We make the `person2` object persistent using the `persist()` method in Step 7:
Transaction transaction = session.beginTransaction();
session.persist(person2);
transaction.commit();

5- #### `saveOrUpdate()`

The `saveOrUpdate()` method is used to save or update an object depending on its state (whether it is already persistent or not). We save or update the `person3` object using the `saveOrUpdate()` method in Step 10:
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(person3);
transaction.commit();

6- #### `update()`

The `update()` method is used to update a persistent object. We update the `person2` object using the `update()` method in Step 8:
transaction = session.beginTransaction();
person2.setName(“Somi kaushik”);
session.update(person2);
transaction.commit();

7- #### `merge()`

The `merge()` method is used to merge the state of a detached object into a persistent object. We merge the `person4` object using the `merge()` method in Step 11:
transaction = session.beginTransaction();
Person mergedPerson4 = (Person) session.merge(person4);
transaction.commit();

8- #### `delete()`

The `delete()` method is used to delete a persistent object. We delete the `person1` object using the `delete()` method in Step 12:
transaction = session.beginTransaction();
session.delete(person1);
transaction.commit();

9- #### `remove()`

The `remove()` method is used to make a persistent object detached. We do not use this method in the example code.

10- #### `evict()`

The `evict()` method is used to remove an object from the session cache. We remove the `person2` object from the session cache using the `evict()` method in Step 13:
session.evict(person2);

11- #### `clear()`

The `clear()` method is used to remove all objects from the session cache. We clear the session cache using the `clear()` method in Step 14:
session.clear();

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.