For example:
CopyCode The Code is as follows: hibernatetest. Java
Import onlyfun. Caterpillar .*;
Import net. SF. hibernate .*;
Import net. SF. hibernate. cfg .*;
Import java. util .*;
Public class hibernatetest {
Public static void main (string [] ARGs) throws hibernateexception {
Sessionfactory = new configuration (). Configure (). buildsessionfactory ();
Session session = sessionfactory. opensession ();
List users = session. Find ("from user ");
User updated = NULL;
For (listiterator iterator = users. listiterator (); iterator. hasnext ();){
User user = (User) iterator. Next ();
If (updated = NULL)
Updated = user;
System. Out. println (user. getname () +
"\ N \ Tage:" + User. getage () +
"\ N \ tsex:" + User. getsex ());
}
Updated. setname ("Justin ");
Session. Flush ();
Users = session. Find ("from user ");
Session. Close ();
Sessionfactory. Close ();
For (listiterator iterator = users. listiterator (); iterator. hasnext ();){
User user = (User) iterator. Next ();
System. Out. println (user. getname () +
"\ N \ Tage:" + User. getage () +
"\ N \ tsex:" + User. getsex ());
}
}
}
This Program displays all data in the data table and updates the first data in the data table. The execution result is as follows:
log4j: warn no appenders cocould be found for logger (net. SF. hibernate. cfg. environment ).
log4j: Warn please initialize the log4j system properly.
hibernate: Select user0 _. user_id as user_id, user0 _. name as name, user0 _. sex as sex, user0 _. age as age from user user0 _
caterpillar
Age: 28
sex: m
m Omor
Age: 25
sex: F
bush
Age: 25
sex: m
Becky
age: 35
sex: F
hibernate: update user set name = ?, Sex = ?, Age =? Where user_id =?
hibernate: Select user0 _. user_id as user_id, user0 _. name as name, user0 _. sex as sex, user0 _. age as age from user user0 _
Justin
Age: 28
sex: m
momor
Age: 25
sex: F
bush
Age: 25
sex: m
Becky
Age: 35
sex: F