包阅导读总结
1. 关键词:Hibernate、load()、get()、差异、数据库
2. 总结:
本文详细探讨了 Hibernate 中 `load()` 和 `get()` 方法的区别。`load()` 方法懒加载,返回代理,未找到实体时抛出异常;`get()` 方法立即查询数据库,未找到时返回 `null`。还通过示例和对比说明了它们在初始化、数据库查询、未找到实体时的行为、使用场景和性能影响等方面的差异。
3. 主要内容:
– Hibernate 中 `load()` 和 `get()` 方法常用于从数据库检索对象
– `load()` 方法
– 特点:懒初始化,返回代理,未找到实体抛出异常,适用于只读操作
– 示例:通过特定 ID 检索 `User` 实体,访问属性时触发数据库查询
– `get()` 方法
– 特点:立即查询数据库,未找到返回 `null`,立即初始化
– 示例:通过特定 ID 检索 `User` 实体,立即获取数据
– 关键差异
– 初始化:`load()` 懒加载,`get()` 立即加载
– 数据库查询:`load()` 延迟,`get()` 立即执行
– 未找到实体行为:`load()` 抛异常,`get()` 返回 `null`
– 使用场景:`load()` 预期实体存在且懒加载可接受,`get()` 需立即访问实体数据
– 性能影响:`load()` 可能因延迟加载提升性能,`get()` 立即有影响
– 结论:阐述了两种方法的差异,`load()` 懒加载有特定场景,`get()` 立即获取数据有适用情况
思维导图:
文章地址:https://www.javacodegeeks.com/hibernate-load-and-get-whats-the-difference.html
文章来源:javacodegeeks.com
作者:Omozegie Aziegbe
发布时间:2024/7/12 10:22
语言:英文
总字数:1031字
预计阅读时间:5分钟
评分:84分
标签:Hibernate,Java,ORM,load() Method,get() Method
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
Two commonly used methods in Hibernate for retrieving objects from the database are load() and get(). Though they appear similar, they exhibit distinct differences in behaviour and use cases. This article explores these differences in detail.
1. load()
Method
The load()
method is used to retrieve an entity from the database by its primary key. However, it does so lazily, which means it returns a proxy of the entity instead of the actual entity itself. The actual database query is executed only when a property of the entity is accessed.
1.1 Characteristics of load()
- Lazy Initialization: Returns a proxy without hitting the database immediately.
- Throws an Exception: Throws an
ObjectNotFoundException
if the entity is not found. - Efficient for Read-Only Operations: Useful when you need a reference to an entity to set associations without requiring the entity’s actual data.
1.2 Example of load() in Hibernate
User Entity: Let’s define a simple User
entity.
@Entity@Table(name = "users")public class User implements Serializable { @Id private Long id; private String name; private String email; // Getters and setters 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
Here is an example demonstrating the use of load()
public class HibernateLoadExample { public static void main(String[] args) { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Long userId = 3L; // use load method User user = session.load(User.class, userId); System.out.println("User loaded, but not initialized yet."); System.out.println("User name: " + user.getName()); // Triggers database query }}
In this example, we use the load()
method to retrieve a User
entity with a specific ID (3L). The key characteristic of load()
is its lazy initialization. When session.load(User.class, userId)
is called, Hibernate returns a proxy object rather than executing a database query immediately. The proxy object represents the User
entity and will defer loading the actual data until a property of the entity is accessed.
Output When an ID is Found:
When the entity with the specified ID (1L) exists in the database, accessing a property of the proxy object, such as user.getName()
, triggers a database query to load the actual data of the User
entity. The console will print the following:
Output When an ID is Not Found:
If the entity with the specified ID does not exist in the database, accessing any property of the proxy object will result in an ObjectNotFoundException
. The console will print the stack trace of the exception:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=?Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.jcg.hibernateloadexample.User#30]
2. get()
Method
The get()
method retrieves an entity from the database immediately. It directly hits the database and returns the actual entity object. When you call get(class, id)
, Hibernate performs the following actions:
- Checks the Session Cache: It first looks for the object identified by the provided identifier in the Hibernate session cache. If the object exists in the cache, it’s returned directly, avoiding a database hit.
- Fetches from Database (if not in Cache): If the object is not found in the cache, Hibernate fires a database query to retrieve the data based on the identifier.
- Returns the Object (or Null): Upon successful retrieval,
get()
returns the fully initialized object. If no object exists with the given identifier,get()
returnsnull
.
2.1 Characteristics of get()
- Immediate Database Hit: Executes the query and retrieves the entity immediately.
- Returns Null: Returns
null
if the entity is not found. - Eager Initialization: Useful when you need the entity’s data immediately.
2.2 Example of get() in Hibernate
Here is an example demonstrating the use of get()
public class HibernateGetExample { public static void main(String[] args) { // Setup SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); // Begin transaction session.beginTransaction(); // Get entity Long entityId = 1L; User entity = session.get(User.class, entityId); System.out.println("Entity found: " + entity.getName()); }}
In this example, we use the get()
method to retrieve a User
entity with a specific ID (1L). The get()
method immediately executes a database query to fetch the entity’s data and returns the actual User
object. This method is not lazy and directly interacts with the database.
Output When an ID is Found:
When the entity with the specified ID (1L) exists in the database, the get()
method retrieves the entity immediately. The console will print the following:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=?Entity found: John Doe
This output indicates that the User
entity was successfully retrieved.
Output When ID is Not Found:
If the entity with the specified ID does not exist in the database, the get()
method returns null
. The console will print the following:
Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=?Exception in thread "main" java.lang.NullPointerException
3. Key Differences
Here is a comparison of the load()
and get()
methods in Hibernate.
Feature | load() | get() |
---|---|---|
Initialization | Lazy (returns a proxy) | Eager (retrieves the actual entity) |
Database Query | Deferred until a property is accessed | Executed immediately |
Behaviour if Entity Not Found | Throws ObjectNotFoundException |
Returns null |
Use Case | When the entity is expected to exist and lazy loading is acceptable | When immediate access to entity data is needed |
Performance Impact | May improve performance due to deferred loading | Immediate impact due to instant query |
4. Conclusion
In this article, we explored the differences between Hibernate’s load()
and get()
methods. We discussed how load()
provides lazy initialization, returning a proxy and throwing an exception if the entity is not found. On the other hand, get()
retrieves the entity immediately, returning null
if the entity is absent, which is useful when the entity’s data is required right away.
5. Download the Source Code
This article explored the difference between Hibernate load() and get() methods.