Hibernate 中如果直接使用Session.update(Object o),會把這個表中的所有欄位更新一遍。
如果你沒有對你需要更新的欄位以外的欄位賦值,那麼這些欄位會被置空。
public class TeacherTest
{
@Test
public void update()
{
Session session = HibernateUitl.getSessionFactory().getCurrentSession();
session.beginTransaction();
Teacher t = (Teacher) session.get(Teacher.class, 3);
t.setName("yangtb2");
session.update(t);
session.getTransaction().commit();
}
}
Hibernate 執行的SQL語句:
Hibernate:
update
Teacher
set
age=?,
birthday=?,
name=?,
title=?
where
id=?
我們只更改了Name屬性,而Hibernate 的sql語句 把所有欄位都更改了一次。
這樣要是我們有欄位是文本類型,這個類型儲存的內容是幾千,幾萬字,這樣效率會很低。
那麼怎麼只更改我們更新的欄位呢?有三中方法:
1.XML中設定property 標籤 update = "false" ,如下:我們設定 age 這個屬性在更改中不做更改
<property name="age" update="false"></property>
<property name="age" update="false"></property>
在Annotation中 在屬性GET方法上加上@Column(updatable=false)
@Column(updatable=false)
public int getAge() {
return age;
}
我們在執行 Update方法會發現,age 屬性 不會被更改
Hibernate:
update
Teacher
set
birthday=?,
name=?,
title=?
where
id=?
缺點:不靈活
2.使用XML中的 dynamic-update="true"
<class name="com.sccin.entity.Student" table="student" 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',t.age = '20' where id = 3");
query.executeUpdate();
session.getTransaction().commit();
}
注意:更新每個欄位之間的逗號不可少,否則報錯。
Hibernate 執行的SQL語句:
Hibernate:
update
Teacher
set
name='yangtianb', age='20'
where
id=3
這樣就只更新了我們更新的欄位
自己整理的一些方法:
1、使用hidden標籤,把不需要的欄位也查出來,然後在返回去。
2、再查一邊資料庫,聲明一個新的對象,再把頁面傳過來的資料set進去,儲存這個新聲明的對象
原帖地址:http://www.cnblogs.com/hyteddy/archive/2011/07/21/2113175.html