Hibernate笔记6(get和load)
来源:互联网 发布:自学编程难不难 编辑:程序博客网 时间:2024/06/05 19:23
session.load()和session.get()
load
Object load(Class theClass,
Serializable id)
throws HibernateExceptionReturn the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand, when a non-identifier method is accessed.
You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.
Parameters:
theClass - a persistent class
id - a valid identifier of an existing persistent instance of the class
Returns:
the persistent instance or proxy
Throws:
HibernateException
get
Object get(Class clazz,
Serializable id)
throws HibernateExceptionReturn the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.)
Parameters:
clazz - a persistent class
id - an identifier
Returns:
a persistent instance or null
Throws:
HibernateException
load与get的区别
1.load返回的是一个代理,get返回一个原对象的实例;
@Test
public void testLoad() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Notes note = (Notes)session.load(Notes.class, 6);
session.getTransaction().commit();
System.out.println(note.getFileName());
}
@Test
public void testGet() {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Notes note = (Notes)session.get(Notes.class, 6);
session.getTransaction().commit();
System.out.println(note.getFileName());
}
这两个方法执行后,testGet()可以正确执行,而testLoad()会抛出如下异常:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
2.load是在对象已经存在的假设前提下的,所以对于一个不存在的id,load不会出错,会
返回一个代理,只有当这个代理被使用的时候才会报错,抛出如下异常:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.cat.model.Notes#1]
get方法则会在get被调用的时候抛出:
java.lang.NullPointerException
- Hibernate笔记6(get和load)
- 【Hibernate学习笔记】get和load区别
- hibernate get()和load()
- hibernate get()和load()
- hibernate load 和get
- hibernate get 和load
- Hibernate 笔记5 load和get方法的区别
- hibernate load和get区别
- hibernate load和get区别
- Hibernate get和load区别
- hibernate get 和 load 区别
- Hibernate之get()和load()
- Hibernate get和load区别
- Hibernate get和load区别
- Hibernate get和load区别
- Hibernate get和load区别
- Hibernate get和load区别
- Hibernate get和load区别
- 关于在Eclipse中J2ME插件的几种安装法
- 关于在Eclipse中J2ME插件的几种安装法
- 关于在Eclipse中的构建期间出问题解决办法
- 成长历程
- cron,linux定时执行工具详解及实例
- Hibernate笔记6(get和load)
- 9000小型机vg00中磁盘损坏更换方法
- 一些说到心坎里的话
- 进程管理-----黑白棋子之分
- 改变你生活的50种方式
- 虚拟机下Linux上网配置
- 感恩母亲
- 嵌入式linux系统开发概述之五----文件系统(FileSystem)
- 请教个问题,我是新手