
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();
[…] Step 6 β 11 Methods of hibernate […]