# Hibernate 4 – 获取延迟加载的实体引用

> 原文： [https://howtodoinjava.com/hibernate/hibernate-4-example-to-get-entity-reference-for-lazy-loading/](https://howtodoinjava.com/hibernate/hibernate-4-example-to-get-entity-reference-for-lazy-loading/)

根据 Wikipedia 的定义， [**延迟加载**](https://en.wikipedia.org/wiki/Lazy_loading "lazy loading")是一种设计模式，通常用于计算机编程中，以将对象的初始化推迟到需要的时间点。 我们知道，在 Hiberate 映射中，可以通过在 Hiberate 映射注解中指定`fetch = FetchType.LAZY`来完成延迟加载。 例如：

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

```

关键是仅在定义两个实体之间的映射时才应用它。 如果已经在`DepartmentEntity`中定义了以上实体，则如果您获取`DepartmentEntity`，则`EmployeeEntity`将被延迟加载。

但是，如果您要延迟加载`DepartmentEntity`本身，即**主实体本身应延迟加载**，该怎么办。

可以通过在`IdentifierLoadAccess`类中使用[**`getReference()`**](http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/IdentifierLoadAccess.html#getReference%28java.io.Serializable%29 "IdentifierLoadAccess")方法解决此问题。

让我们通过此示例了解用法。

作为参考，最新的 Hiberate Maven 依赖项如下：

```java
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>4.3.0.Beta3</version>
</dependency>

```

现在，我有一个主实体类`EmployeeEntity`，它可以具有多个属性以及与其他实体的映射。

**`EmployeeEntity.java`**

```java
@Entity
@Table(name = "Employee", uniqueConstraints = {
		@UniqueConstraint(columnNames = "ID"),
		@UniqueConstraint(columnNames = "EMAIL") })
public class EmployeeEntity implements Serializable {

	private static final long serialVersionUID = -1798070786993154676L;

	@Id
	@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
}

```

我想在我的代码中延迟加载的主实体之上延迟加载，即我可以在一个地方获取实体的引用，但实际上可能需要在另一个地方进行引用。 仅在需要时，我才想初始化或加载其数据。 到时候为止，我只想参考。

让我们在代码示例中这样做：

**`TestHibernate.java`**

```java
public class TestHibernate
{
	public static void main(String[] args) 
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		//Add new Employee object
		EmployeeEntity emp = new EmployeeEntity();
		emp.setEmail("demo-user@mail.com");
		emp.setFirstName("demo");
		emp.setLastName("user");
		//Save entity
		session.save(emp);

		session.getTransaction().commit();
		session.close();

		session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		//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
		System.out.println(empGet.getFirstName());
		System.out.println(empGet.getLastName());

		session.getTransaction().commit();
		HibernateUtil.shutdown();
	}
}

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=?

demo
user

```

要下载以上教程的源代码，请单击下面的下载链接。

**祝您学习愉快！**