SoFunction
Updated on 2025-04-13

jsp Hibernate Introduction Tutorial Page 3/3


Hibernate provides a saveOrUpdate() method, which provides a unified operation interface for data storage or update. By setting the unsaved-value of the <id> tag when defining the image file, it determines what is the new value and what is the existing value that must be updated:

Copy the codeThe code is as follows:

<id name="id" type="string" unsaved-value="null">
<column name="user_id" sql-type="char(32)" />
<generator class=""/>
</id>

unsaved-value
Values ​​that can be set include:
any - Always stored
none - always updated
null - Save when id is null (preset)
valid - stored when id is null or specified value
After setting this way, you can use (updated); to replace the (updated); method of the previous program.
If you want to delete data, just use the delete() method and look at an example directly.
Copy the codeThe code is as follows:


import .*;
import .*;
import .*;
import .*;
public class HibernateTest {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = ();
List users = ("from User");
User updated = null;
for (ListIterator iterator = (); (); ) {
User user = (User) ();
if(updated == null)
updated = user;
(() +
"\n\tAge: " + () +
"\n\tSex: " + ());
}
(updated);
users = ("from User");
();
();
for (ListIterator iterator = (); (); ) {
User user = (User) ();
(() +
"\n\tAge: " + () +
"\n\tSex: " + ());
}
}
}

An example of the results of execution is as follows:
log4j:WARN No appenders could be found for logger ().
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_
justin
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F
Hibernate: delete from USER 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_
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F
Hibernate's actions for data update, deletion, etc. are determined by the lazy id value. If you know the id value, you can use the load() method to load the data, for example:
User user = (User) (, id);
For more instructions on the update operation of Hibernate data, you can check out the contents of Chapter 9 of the reference manual.
Previous page123Read the full text