Hibernate 4 – Get Entity Reference for Lazy Loading

By Wikipedia definition, Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. We know that in hibernate lazy loading can be done by specifying “fetch= FetchType.LAZY” in hibernate mapping annotations. e.g.

@ManyToOne ( fetch = FetchType.LAZY )
@JoinColumns( {
		@JoinColumn(name="fname", referencedColumnName = "firstname"),
		@JoinColumn(name="lname", referencedColumnName = "lastname")
		} )
public EmployeeEntity getEmployee() {
	return employee;

The point is that it is applied only when you are defining mapping between two entities. If above entity has been defined in DepartmentEntity then if you fetch DepartmentEntity then EmployeeEntity will be lazy loaded.

But, what if you want to lazy load DepartmentEntity itself i.e. master entity itself should be lazy loaded.

This problem can be solved by using getReference() method inside IdentifierLoadAccess class.

Let’s understand the usage by this example.

For reference, latest hibernate maven dependency is as follows:


Now, I have an master entity class EmployeeEntity which can have multiple attributes and mapping with other entities.


@Table(name = "Employee", uniqueConstraints = {
		@UniqueConstraint(columnNames = "ID"),
		@UniqueConstraint(columnNames = "EMAIL") })
public class EmployeeEntity implements Serializable {
	private static final long serialVersionUID = -1798070786993154676L;
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID", unique = true, nullable = false)
	private Integer employeeId;
	//Use the natural id annotation here
	@NaturalId (mutable = false)
	@Column(name = "EMAIL", unique = true, nullable = false, length = 100)
	private String email;
	@Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
	private String firstName;
	@Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
	private String lastName;

	//Setters and Getters

I want to lazy load above master entity lazy loaded in my code i.e. I can get reference of entity in one place but might be actually needing it another place. Only when I need it, I want to initialize or load its data. Till the time, I want only the reference.

Let’s do this in code example:


public class TestHibernate
	public static void main(String[] args) 
		Session session = HibernateUtil.getSessionFactory().openSession();
		//Add new Employee object
		EmployeeEntity emp = new EmployeeEntity();
		//Save entity
		session = HibernateUtil.getSessionFactory().openSession();
		//Get only the reference of EmployeeEntity for now
		EmployeeEntity empGet = (EmployeeEntity) session.byId( EmployeeEntity.class ).getReference( 1 );
		System.out.println("No data initialized till now; Lets fetch some data..");
		//Now EmployeeEntity will be loaded from database when we need it

Output in console:

Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)

No data initialized till now; Lets fetch some data..

Hibernate: select employeeen0_.ID as ID1_0_0_, employeeen0_.EMAIL as EMAIL2_0_0_, employeeen0_.FIRST_NAME as FIRST3_0_0_, 
employeeen0_.LAST_NAME as LAST4_0_0_ from Employee employeeen0_ where employeeen0_.ID=?


To download the source code of above tutorial, please click on below download link.

Sourcecode Download

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “Hibernate 4 – Get Entity Reference for Lazy Loading”

  1. hi i recently tried Hibernate 4 annotation example, where i m getting communication link failure exception.
    i googled it but i didn’t get proper answer.
    i m using mysql connector 3.0.8. and my database is not in idle mode.
    can u clarify ?


Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.