Introduction
Get() and load() are two methods in hibernate that are used to retrieve data for a specified identifier. They are both members of the Hibernate session class. If no record is accessible in the session cache or the database for the provided identifier, the get() function returns null, but the load() method throws an object not found error.
The get() function retrieves data immediately upon execution, but the load() method produces a proxy object and retrieves data only when object properties are required. As a result, the load() function performs better since it supports slow loading. Because it throws an exception if data is not discovered, we should only use the load() function when we know it exists. We should utilize the get() function to ensure that data exists.
Implementations Of Get() And Load() Methods
Get() Method
@Entity
public class Player {
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
GetExample.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class GetExample {
public static void main(String[] args) {
//get session factory to start transcation
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//Get Example
Player player = (Player) session.get(Player.class, new Integer(2));
System.out.println("Player ID= "+player.getId());
System.out.println("Player Name= "+player.getName());
//Close resources
tx.commit();
sessionFactory.close();
}
}Load() Method
@Entity
public class Player {
@Id
Integer id;
String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
LoadExample.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class LoadExample {
public static void main(String[] args) {
//get session factory to start transcation
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//Load Example
Player player = (Player) session.load(Player.class, new Integer(2));
System.out.println("Player ID= "+player.getId());
System.out.println("Player Name= "+player.getName());
//Close resources
tx.commit();
sessionFactory.close();
}
}





