RSS

持久化对象生命周期

30 Jan

持久化对象生命周期的状态

Transient状态 – 特点是没有主键值
GuestBook gb = new GuestBook();

gb.setName(“Xavier”);
gb.setEmail(“finchan_ding@hotmail.com);

Persistent状态
session.beginTransaction();

GuestBook gb = new GuestBook();

gb.setName(“Xavier”);

gb.setEmail(“finchan_ding@hotmail.com);
session.save(gb)

Detached状态 – 有主键值
Transaction tx = session.beginTransaction();

GuestBook gb = (GuestBook)session.get(GuestBook.class, new Integer(1));

tx.commit();

session.close();
gb.setName(“Nate”);

Removed状态
Transaction tx = session.beginTransaction();

GuestBook gb = (GuestBook) session.get(GuestBook.class, new Integer(1));

session.delete(gb);
tx.commit();

Session对象的“脏”数据检查
Persistent状态的对象受Session的管理,我们对对象的属性的修改,当Session对象调用close(0方法或者Transaction对象执行commit()方法,数据库中对应的数据也会自动跟着进行同步更新。
Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

GuestBook gb = (GuestBook)session.get(GuestBook.class, new Integer(1));

gb.setName(“A”);

tx.commit();
//即便不调用save方法,对上面的Persistent的对象修改依然会作用于DB。

Session接口的其他核心方法
saveOrUpdate()方法 – 自动判断对象有没有主键值,如果有,则update,如果没有主键值,则save
Transacion tx = session.beginTransaction();

GuestBook gb = (GuestBook) session.get(GuestBook.class, new Integer(1));

tx.commit();

gb.setName(“New Name”);

session = sessionFactory.getCurrentSession();

tx = session.beginTransaction();

session.saveOrUpdate(gb);
tx.commit();

flush()方法
它是同步清理一级或者二级缓存,在session关闭前应该调用flush方法,如果使用getCurrentSession则会自动调用这个方法,不用显示调用。只需要在cfg.xml中配置一下current_session_context_class = thread

close()方法
是关闭session方法,如果session和事务Transaction绑定在一起,当事务提交,这个session会自动调用close方法。只需要在cfg.xml中配置一下current_session_context_class = thread

不可更改的持久化对象
所操作的持久化对象是只读的,只进行读取,不进行更新和删除的操作,但是不影响插入新Row的操作
<class name=“com.example.LogInfo” table=“loginfo” mutable=“false”>
mutable=”false”为表示不可以更改,只能读取

Advertisements
 
Leave a comment

Posted by on 01/30/2011 in HIBERNATE

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: