Hibernate3---持久化对象的状态

1、Hibernate的CRUD操作

(1)save

 Serializablesave(Object object)
          Persist the given transient instance, first assigning a generated identifier.

(2)get/load

     

 Objectget(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.

 Object

load(Class theClass,Serializable id)
          Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.

区别:

    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

 voidupdate(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

 voiddelete(Object object)
          Remove a persistent instance from the datastore.

    方式同update。

2、持久化对象的状态

(1)transient状态

       在数据库中没有与之匹配的记录,没有被持久化管理器---session管理。

(2)persistent状态
       在数据库中有与之匹配的记录,并且被session管理。

(3)detached状态

         在数据库中有与之匹配的记录,但没有被session管理。



 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值