Hibernate 中 get() 和 load() 的区别
在 Hibernate 中,get() 和 load() 是两种用于根据给定标识符获取数据的的方法。它们都属于 Hibernate Session 类。如果在 Session 缓存或数据库中找不到给定标识符对应的行,则 get() 方法返回 null,而 load() 方法则抛出对象未找到异常。
| 序号 | 关键点 | Get() | Load() |
|---|---|---|---|
1 | 基础 | 用于根据给定标识符从数据库中获取数据 | 也用于根据给定标识符从数据库中获取数据 |
2 | 空对象 | 如果找不到给定标识符对应的对象,则返回空对象 | 将抛出对象未找到异常 |
3 | 延迟加载或立即加载 | 返回完全初始化的对象,因此此方法立即加载对象 | 始终返回代理对象,因此此方法延迟加载对象 |
4 | 性能 | 它比 load() 慢,因为它返回完全初始化的对象,这会影响应用程序的性能 | 它稍快。 |
5. | 用例 | 如果不确定对象是否存在,则使用 get() 方法 | 如果确定对象存在,则使用 load() 方法 |
Hibernate 中 Get() 的示例
@Entity
public class User {
@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;
}
}
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
User user = (User) session.get(User.class, new Integer(2));
System.out.println("User ID= "+user.getId());
System.out.println("User Name= "+user.getName());
//Close resources
tx.commit();
sessionFactory.close();
}
}Hibernate 中 Load() 的示例
@Entity
public class User {
@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;
}
}
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
User user = (User) session.load(User.class, new Integer(2));
System.out.println("User ID= "+user.getId());
System.out.println("User Name= "+user.getName());
//Close resources
tx.commit();
sessionFactory.close();
}
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP