首页 > 代码库 > Hibernate 持久化对象状态
Hibernate 持久化对象状态
持久化对象PO类状态
1.状态分类
transient 瞬时态:hibernate的session缓存中没有存放,数据库中没有数据。例如新建的po类,没有OID值
persistent 持久态:hibernate的session缓存中存放,数据库中最终会有。例如save(po) 完成commit操作,有OID值
detached 脱管态:hibernate的session缓存中没有,数据库中有数据。脱离session的管理,有OID值
2.OID
OID:hibernate用于标记PO类
java区分对象:地址
数据 区分数据:主键不同
例如:
new Student().setSid(1)
new Student().setSid(1)
认为两个相同PO类
3.状态之间的转换
瞬时态:
转换持久态:save() | saveorUpdate() 如果有OID将执行saveorUpdate(),没有OID将执行save()
脱管态:手动设置OID
Student stu = new Student(); //瞬时态
stu.setSid(1) //脱管,如果数据库中OID对应数据不存在,抛出异常
持久态:
瞬时态:执行delete() 记住。网上所说是:删除态,官方没有给出
脱管态:evict、close、clear
evict():将指定PO类从session中移除
clear():将session缓存清除,清除所有
close():session关闭不存在session缓存
脱管态:
瞬时态:执行delete() 手动移除OID
持久态:执行update()、saveorUpdate()
4.一级缓存
一级缓存:指hibernate session级别的缓存,在session缓存数据
get()通过id查询PO类,将查询的结果缓存到一级缓存(session)
代码如下
package cn.hibernate.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import cn.hibernate.bean.Student;
public class CacheTest {
private SessionFactory factory = new Configuration()
.configure().addClass(Student.class)
.buildSessionFactory();
@Test
public void demo01(){
Session session = factory.openSession();
//查询id为1的Student对象
/*Hibernate:
load cn.hibernate.bean.Student select
student0_.sId as sId0_0_,
student0_.sName as sName0_0_
from
Student student0_
where
student0_.sId=?
Student [sId=1, sName=333]
*/
Student student=(Student)session.get(Student.class, 1);
System.out.println(student);
}
@Test
public void demo02(){
Session session = factory.openSession();
//查询两次id为1的Student对象,按理应该产生两条sql语句,其实只有一条。但是出现了两个相同对象的输出结果
/*Hibernate:
load cn.hibernate.bean.Student select
student0_.sId as sId0_0_,
student0_.sName as sName0_0_
from
Student student0_
where
student0_.sId=?
Student [sId=1, sName=333]
Student [sId=1, sName=333]
*/
Student student=(Student)session.get(Student.class, 1);
System.out.println(student);
//调用evict()方法清除session中student对象进一步查看产生sql语句
// session.evict(student);
System.out.println("********************************************");
/*Hibernate:
load cn.hibernate.bean.Student select
student0_.sId as sId0_0_,
student0_.sName as sName0_0_
from
Student student0_
where
student0_.sId=?
Student [sId=1, sName=333]
Hibernate:
load cn.hibernate.bean.Student select
student0_.sId as sId0_0_,
student0_.sName as sName0_0_
from
Student student0_
where
student0_.sId=?
Student [sId=1, sName=333]
*/
Student student1=(Student)session.get(Student.class, 1);
System.out.println(student1);
}
}
Hibernate 持久化对象状态