我试图在hibernate session.save()中为保存学生信息的代码示例.在那里,学生姓名,班级,教师ID.
表:学生
SNO SNAME SCLASS TNO
----------- ----------------------------------------
1 J D Alex 3 1
2 Goaty 2 2
3 J D Paul 7 1
Run Code Online (Sandbox Code Playgroud)
码:-
Transaction tx1=session1.beginTransaction();
Object o2=session1.get(Student.class,new Integer(3));
((Student)o2).setSclass("8");
session1.save(o2);
log.info("loadStdYearlyInfo:class "+((Student)o2).getSclass());
tx1.commit();
session1.close();
Run Code Online (Sandbox Code Playgroud)
保存数据并看到输出后,类值更新为8,学生ID为3
SNO SNAME SCLASS TNO
----------- ----------------------------------------
1 J D Alex 3 1
2 Goaty 2 2
3 J D Paul 8 1
[07/May/2012:10:03:06] info ( 3500): CORE3282: stdout: Hibernate: /* load com.aims.beans.Student */ select student0_.sno as sno0_, student0_.sname as sname1_0_, student0_.sclass as sclass1_0_, student0_.tno as tno1_0_ from student student0_ where student0_.sno=?
[07/May/2012:10:03:06] info ( 3500): CORE3282: stdout: loadStdYearlyInfo:class 8
[07/May/2012:10:03:06] info ( 3500): CORE3282: stdout: Hibernate: /* update com.aims.beans.Student */ update student set sname=?, sclass=?, tno=? where sno=?
[07/May/2012:10:03:06] info ( 3500): CORE3282: stdout: loadStdYearlyInfo2
Run Code Online (Sandbox Code Playgroud)
如何更新数据库中的学生类值?.save意味着插入数据.但是这里的值已更新.如果有任何问题,请告诉我.如果有任何错误,那么问题对不起.
这是Hibernate的预期行为.
当一个记录由一个hibernate会话加载时,它的实例将处于持久状态并由该会话管理.如果更改持久性实例的值,则将它们视为脏.在刷新过程中(即Session.flush()
),hibernate将找出所有脏实例(我们称之为此过程automatic dirty checking
)并生成并发出必要的SQL以更新相应的DB记录以确保DB记录具有相同的状态作为JVM中保存的相应实例.
休眠会话的刷新行为由确定FlushMode
.默认情况下,FlushMode.AUTO
这意味着 session.flush()
在提交事务或执行查询之前将自动调用.因此,在您的代码中,虽然您没有session.flush()
显式调用,但仍会发生刷新过程以发出这些UPDATE语句.
关于代码的一些评论:
Transaction tx1=session1.beginTransaction();
/**
* o2 is the in the persistent state and managed by session1
*/
Object o2=session1.get(Student.class,new Integer(3));
/**
*As the value of o2 is changed , it becomes dirty and hibernate will issue an UPDATE SQL
*for it during flushing.
*/
((Student)o2).setSclass("8");
/**
* save() only has effect on the transient instance. Nothing will
* be done when calling it on the persistent instance . So removing this line of code
* still produces the same result.
*/
session1.save(o2);
log.info("loadStdYearlyInfo:class "+((Student)o2).getSclass());
/**
*I believe default FlushMode (FlushMode.AUTO) is used in here ,so session.flush() will be invoked implicitly before tx1.commit().
*Automatic dirty checking occurs and UPDATE SQL is generated and issued to the DB
*to update the dirty o2 instance
*/
tx1.commit();
session1.close();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4861 次 |
最近记录: |