jsp Hibernate入门教程第1/3页

编程学习 2021-07-05 11:23www.dzhlxh.cn编程入门
如果您是在同一个Session中取出数据并想要马上进行更新,则只要先查询并取出对象,透过setXXX()方法设定好新的值,然后呼叫session.flush()即可在同一个Session中更新指定的数据
例如:
代码如下:

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());
}
}
}

 这个程序会显示数据表中的所有数据,并将数据表中的第一笔数据更新,一个执行的结果如下:
log4j:WARN No appenders could 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
1

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板