Java Persistence with Hibernate concept 1 -- automatic dirty checking, cascading save. transactional write-behind

//  Third unit of work
Session thirdSession  =
HibernateUtil.getSessionFactory().openSession();
Transaction thirdTransaction 
=  thirdSession.beginTransaction();

//  msgId holds the identifier value of the first message
message  =  (Message) thirdSession.get( Message. class , msgId );
message.setText( 
" Greetings Earthling "  );
message.setNextMessage(
new  Message(  " Take me to your leader (please) "  )
);

thirdTransaction.commit();
thirdSession.close();

This code calls three SQL statements inside the same database transaction: 

 

select  m.MESSAGE_ID, m.MESSAGE_TEXT, m.NEXT_MESSAGE_ID
from  MESSAGES m
where  m.MESSAGE_ID  =   1

insert   into  MESSAGES (MESSAGE_ID, MESSAGE_TEXT, NEXT_MESSAGE_ID)
values  ( 2 ' Take me to your leader (please) ' null )

update  MESSAGES
set  MESSAGE_TEXT  =   ' Greetings Earthling ' , NEXT_MESSAGE_ID  =   2
where  MESSAGE_ID  =   1

 

Notice how Hibernate detected the modification to the text and nextMessage
properties of the first message and automatically updated the database—Hibernate
did automatic dirty checking. This feature saves you the effort of explicitly asking
Hibernate to update the database when you modify the state of an object
inside a unit of work. Similarly, the new message was made persistent when a reference
was created from the first message. This feature is called cascading save. It
saves you the effort of explicitly making the new object persistent by calling
save(), as long as it’s reachable by an already persistent instance.
Also notice that the ordering of the SQL statements isn’t the same as the order
in which you set property values. Hibernate uses a sophisticated algorithm to
determine an efficient ordering that avoids database foreign key constraint violations
but is still sufficiently predictable to the user. This feature is called transactional
write-behind
.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值