For example:
Copy codeThe 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 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 will display all the data in the data table and update 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
Momor
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