Hibernate Methods

Below are the different Hibernate methods define to define and manipulate the data.

save(), saveOrUpdate() and persist()

These methods helps us to insert and update object in to database.

save() method we use to insert new or fresh object in database.

saveOrUpdate() method we use to insert brand new or update existing object in database.

persist() also use to save data in database. The only difference is of return type. persist() will return void and save() will return serializable object.

Note: We will always be using only one function out of

load() and get()

load() method will help us to get data from database depending on id.
In below example, we are fetching user from database having userId 1.

It will throw ObjectNotFoundException if object not found.

It will return proxy object in case object not found.

get() method also use to fetch data from database else it will return null. It will load data from cache if not found in database.

Performance wise load() method is NOT recommended, every time it looks for the data in database as it eagerly load the data.

Eager and lazy loading

It is a data loading technique. Hibernate loads data from database using eager and lazy loading.

Eager loading: Data will get load as soon as it is loaded or required code is initialized.

Lazy loading: Data will not get until it is actually required.

delete()

delete() method will help us to delete particular user from database.

In below example, we are checking if particular user exist in database or not. If yes, delete user.

In below code snippet, we are asking hibernate to delete user having userId 1.

list()

list() method will return complete list of users from database table using createQuery() method from session interface.

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0