253
魔獸
Hibernate之update(1)——更新部分字段
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進去,保存這個新聲明的對象
最後更新:2017-04-03 16:49:27