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(); } }
廣告