1、Hibernate的CRUD操作
(1)save
Serializable | save(Object object) Persist the given transient instance, first assigning a generated identifier. |
(2)get/load
Object | get(Class clazz,Serializable id) Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. |
|
区别:
A:get 不支持lazy(延迟)加载,load支持延迟加载,如下:
User u=(User)session.get(User.class, "8a8ae98a3174cb17013174cb185a0001");
当执行到此句时,即刻发出sql查询语句,加载User对象,然后持久化对象状态变为persistent
User u=(User)session.load(User.class, "8a8ae98a3174cb17013174cb185a0001");
System.out.println("u.name="+u.getName());
当用load 方法时,执行到第一句不会发出sql查询语句,load 方法实现了lazy---延迟加载;当第二句使用时才发出sql查询语句。
B:当数据库中要查询的记录为空时,get 方式返回null,而load 方式会抛出org.hibernate.ObjectNotFoundException异常。
(3)update
void | update(Object object) Update the persistent instance with the identifier of the given detached instance. |
前提是数据库中有该记录:
User u=new User();
u.setId("8a8ae98a3174cb17013174cb185a0001");
u.setName("update哥");
session.update(u);
如果使用这种手动的方式构造一个detached对象,其他的字段会变为null。
因此更新记录的方法是首先get/load,然后再update。
(4)delete
void | delete(Object object) Remove a persistent instance from the datastore. |
方式同update。
2、持久化对象的状态
(1)transient状态
在数据库中没有与之匹配的记录,没有被持久化管理器---session管理。
(2)persistent状态
在数据库中有与之匹配的记录,并且被session管理。
(3)detached状态
在数据库中有与之匹配的记录,但没有被session管理。