Topic 6 – 10 Methods of hibernate

image 2

Play Store Application link – Hibernate – in 10 steps – Apps on Google Play

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- evict() method

10- 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

Github project link – https://github.com/kuldeep101990/MethodsHibernate

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;
    }
 
    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 (hibernate.cfg.xml)

<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/methodsHibernate?createDatabaseIfNotExist=true</property>
        <property name="connection.username">root</property>
        <property name="connection.password">D@2491219997k</property>
 
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
 
        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
 
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
 
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
         <property name="hibernate.use_sql_comments">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
 
        <!-- Mapping files -->
        <mapping resource="person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

3- Hibernate Mapping File (person.hbm.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <hibernate-mapping>
    <class name="methodsHibernate.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>

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

import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateInheritanceExample {

    public static void main(String[] args) {

        System.out.println("Initializing Hibernate configuration...");
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml"); 

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession();

        try {
            // Creating a new Person object
            System.out.println("Creating a new Person object...");
            Person person1 = new Person();
            person1.setName("John Doe");
            person1.setDob(new Date());

            // save(): Immediately generates an insert query and saves the object in the database, returns the identifier of the saved object.
            System.out.println("Saving Person object using save() method...");
            Transaction transaction = session.beginTransaction(); 
            session.save(person1); 
            transaction.commit(); 
            System.out.println("Person saved with ID: " + person1.getId());

            // get(): Fetches an object from the database using the identifier. Returns null if not found.
            System.out.println("Fetching Person using get() method...");
            Person fetchedPerson = (Person) session.get(Person.class, person1.getId());
            if (fetchedPerson != null) {
                System.out.println("Fetched person using get(): " + fetchedPerson.getName());
            } else {
                System.out.println("No person found with the given ID using get().");
            }
            
           // load(): Fetches a proxy object of the entity without hitting the database immediately, throws an exception if the entity does not exist when accessed.
            System.out.println("Fetching Person using load() method...");
            try {
                Person loadedPerson = (Person) session.load(Person.class, person1.getId());
                System.out.println("Fetched person using load(): " + loadedPerson.getName());
            } catch (Exception e) {
                System.out.println("Exception occurred while loading person: " + e.getMessage());
            }

            // persist(): Similar to save(), but does not return the identifier, follows JPA specification and ensures the object is only in the persistent state if the transaction is committed.
            System.out.println("Creating another Person object...");
            Person person2 = new Person();
            person2.setName("Jane Doe");
            person2.setDob(new Date());

            System.out.println("Saving Person object using persist() method...");
            transaction = session.beginTransaction();
            session.persist(person2); 
            transaction.commit();
            System.out.println("Person saved with ID: " + person2.getId());

            // update(): Updates the data of a persistent object in the database, should be used for objects already managed by the session.
            System.out.println("Updating Person object using update() method...");
            transaction = session.beginTransaction();
            person2.setName("Jane Smith"); 
            session.update(person2); 
            transaction.commit();
            System.out.println("Person updated: New Name = " + person2.getName());

            // saveOrUpdate(): Saves a new object or updates an existing one depending on its identifier, useful for handling both new and detached objects.
            System.out.println("Creating and saving/updating another Person using saveOrUpdate()...");
            Person person3 = new Person();
            person3.setName("Michael Johnson");
            person3.setDob(new Date());

            transaction = session.beginTransaction();
            session.saveOrUpdate(person3); 
            transaction.commit();
            System.out.println("Person saved/updated with ID: " + person3.getId());

            // merge(): Copies the state of a detached object into the persistent context, returns a managed instance of the object.
            System.out.println("Creating and merging a detached Person object...");
            Person detachedPerson = new Person();
            detachedPerson.setName("Emily Davis");
            detachedPerson.setDob(new Date());

            transaction = session.beginTransaction();
            Person mergedPerson = (Person) session.merge(detachedPerson); 
            transaction.commit();
            System.out.println("Merged Person details: Name = " + mergedPerson.getName() + ", DOB = " + mergedPerson.getDob());

            // delete(): Removes an object from the database.
            System.out.println("Deleting a Person object using delete() method...");
            transaction = session.beginTransaction();
            session.delete(person1); 
            transaction.commit();
            System.out.println("Person with ID " + person1.getId() + " deleted.");

            // evict(): Removes an object from the session cache but does not affect the database.
            System.out.println("Evicting a Person object from session cache...");
            session.evict(person2); 
            System.out.println("Person with ID " + person2.getId() + " evicted from cache.");

            // clear(): Clears the entire session cache.
            System.out.println("Clearing the entire session cache...");
            session.clear(); 
            System.out.println("Session cache cleared.");

        } catch (Exception e) {
            System.out.println("An error occurred: Rolling back transaction...");
            if (session.getTransaction() != null) session.getTransaction().rollback();
            e.printStackTrace();
        } finally {
            // Close the session and SessionFactory
            System.out.println("Closing session and SessionFactory...");
            session.close(); 
            sessionFactory.close(); 
            System.out.println("Hibernate session and SessionFactory closed successfully.");
        }
    }
}

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- #### `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);

10- #### `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();

19 comments

  1. What i do not realize is actually how you are not actually much more well-liked than you may be now. You’re so intelligent. You realize therefore considerably relating to this subject, produced me personally consider it from numerous varied angles. Its like men and women aren’t fascinated unless it is one thing to do with Lady gaga! Your own stuffs outstanding. Always maintain it up!

  2. Hello there, You’ve done a great job. I will definitely digg it and personally recommend to my friends. I am confident they will be benefited from this website.

  3. Wow that was unusual. I just wrote an extremely long comment but after I clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say excellent blog!

  4. Hello my family member! I want to say that this post is amazing, great written and come with almost all significant infos. I would like to look more posts like this .

  5. I am usually to running a blog and i actually appreciate your content. The article has really peaks my interest. I am going to bookmark your site and maintain checking for new information.

  6. It’s impressive that you are getting thoughts from this piece of writing as well as from our argument made at this time.

  7. Yet another thing to mention is that an online business administration course is designed for scholars to be able to easily proceed to bachelor’s degree programs. The Ninety credit diploma meets the other bachelor diploma requirements and once you earn your associate of arts in BA online, you will have access to the latest technologies in this particular field. Several reasons why students need to get their associate degree in business is because they may be interested in this area and want to find the general education necessary just before jumping in a bachelor education program. Thanks for the tips you actually provide with your blog.

  8. That is a very good tip especially to those new to the blogosphere. Short but very accurate information… Many thanks for sharing this one. A must read article!

  9. Hello very nice web site!! Man .. Beautiful .. Amazing .. I will bookmark your site and take the feeds also? I am satisfied to seek out so many useful information here in the put up, we want work out extra techniques on this regard, thank you for sharing.

  10. Heya! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the outstanding work!

  11. I’m not sure why but this web site is loading extremely slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later and see if the problem still exists.

  12. Interesting post here. One thing I would really like to say is most professional domains consider the Bachelor Degree just as the entry level requirement for an online college degree. Though Associate Qualifications are a great way to start, completing your own Bachelors presents you with many opportunities to various jobs, there are numerous online Bachelor Diploma Programs available through institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another thing is that many brick and mortar institutions provide Online variations of their college diplomas but generally for a considerably higher payment than the institutions that specialize in online degree programs.

  13. With the whole thing that seems to be building within this specific area, your points of view tend to be relatively radical. Nevertheless, I beg your pardon, but I do not give credence to your entire idea, all be it radical none the less. It seems to everybody that your commentary are generally not totally validated and in actuality you are generally your self not really totally confident of your assertion. In any case I did appreciate reading through it.

  14. When someone writes an piece of writing he/she keeps the thought of a user in his/her brain that how a user can know it. So that’s why this paragraph is outstdanding.

Leave a Reply

Your email address will not be published. Required fields are marked *