hibernate 中如果直接使用
Session.update(Object o);
會把這個表中的所有字段更新一遍。
比如:
public class Teacher Test { @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 這個屬性在更改中不做更改
在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.第2種方法··使用XML中的 dynamic-update="true"
<classname="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();
}
Hibernate 執行的SQL語句:
Hibernate:
update
Teacher
set
name='yangtianb'
where
id=3
這樣就只更新了我們更新的字段·····