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);
我本想根據str判斷,做出不同的更新策略,但是對于同一個time,Hibernate 的sql語句把所有字段都更改了一次(沒有被set的值,Hibernate會直接賦值空)。
那么怎么只更改我們更新的字段呢?
有三種方法:
1.XML中設置property 標簽 update = "false" ,如下:我們設置 age 這個屬性在更改中不做更改
<property name="age" update="false"></property>
在Annotation中在屬性GET方法上加上@Column(updatable=false)
@Column(updatable=false) public int getAge() { return age; }
2.使用XML中的 dynamic-update="true"
<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(); }
原文轉載自: 點擊打開鏈接