1. 用来更新detached对象,更新完成后转为persistent状态
2. 更新transient对象会报错
3. 更新自己设定id的transient对象可以(数据库有对应记录)
4. persistent状态的对象只要设定(如:t.setName…)不同字段就会发生更新
Hibernate 中如果直接使用 Session.update(Object o); 或则是Session.updateOrUpdate(Object o); 会把这个表中的所有字段更新一遍。
如:
- ExperClass4k e = new ExperClass4k();
- e.setTime(time);
- e.setQ_num(q_num);
- e.setK(k);
- if (str == "finch_fix") {
- e.setFinch_fix_cost1(cost1);
- e.setFinch_fix_cost2(cost2);
- e.setFinch_fix_cost(cost1 + cost2);
- } else if (str == "my") {
- e.setMy_cost1(cost1);
- e.setMy_cost2(cost2);
- e.setMy_cost(cost1 + cost2);
- }
- //session.save(e);
- session.saveOrUpdate(e);
那么怎么只更改我们更新的字段呢?
有四种方法:
1.XML中设置property 标签 update = "false" ,如下:我们设置 age 这个属性在更改中不做更改
- <property name="age" update="false"></property>
- @Column(updatable=false)
- public int getAge() {
- return age;
- }
- <class name="com.sccin.entity.Student" table="student" dynamic-update="true">
OK,这样就不需要在字段上设置了。
但这样的方法在Annotation中没有
3.使用HQL语句(灵活,方便)(推荐)
使用HQL语句修改数据
- public void update(){
- Session session = HibernateUitl.getSessionFactory().getCurrentSession();
- session.beginTransaction();
- Query query = session.createQuery("update Teacher t set t.name = 'yangtianb' where id = 3");
- query.executeUpdate();
- session.getTransaction().commit();
- }
将需要更新的对象加载上来后,利用BeanUtils类的copyProperties方法,将需要更新的值copy到对象中,最后再调用update方法。
注 意:这里推荐使用的方法并非org.apache.comm*****.beanutils包中的方法,而是 org.springframework.beans.BeanUtils中的copyProperties方法。原因是Spring工具类提供了 copyProperties(source, target, ignoreProperties)方法,它能在复制对象值的时候忽略指定属性值,保护某些值不被恶意修改,从而更安全的进行对象的更新。此外,根据一些 测试结果spring中的copyProperties方法效率要高于apache的方法(这点未作进一步验证)。参考代码:
Admin persistent = adminService.load(id);// 加载对象
BeanUtils.copyProperties(admin, persistent, new String[]{"id", "username"});// 复制对象属性值时忽略id、username属性,可避免username被恶意修改
adminService.update(persistent);// 更新对象
本文探讨了Hibernate框架中如何实现部分字段的更新操作,而非更新整个对象的所有字段。通过配置XML、使用注解、启用动态更新及使用HQL语句等方式,实现了更加灵活且高效的更新策略。
1万+

被折叠的 条评论
为什么被折叠?



