如何使hibernate中的update()方法只更新部分字段

Hibernate 中若是直接使用sql

Session.update(Object o);session

會把這個表中的全部字段更新一遍。spa

好比:.net

view plaincopy to clipboardprint?
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(); 

}
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();
}
}ip

Hibernate 執行的SQL語句:ci

view plaincopy to clipboardprint?
Hibernate: 
update 
Teacher 
set 
age=?, 
birthday=?, 
name=?, 
title=? 
where 
id=?
Hibernate:
update
Teacher
set
age=?,
birthday=?,
name=?,
title=?
where
id=?get

咱們只更改了Name屬性,而Hibernate 的sql語句 把全部字段都更改了一次。it

這樣要是咱們有字段是文本類型,這個類型存儲的內容是幾千,幾萬字,這樣效率會很低。io

那麼怎麼只更改咱們更新的字段呢?table

有三中方法:

1.XML中設置property 標籤 update = "false" ,以下:咱們設置 age 這個屬性在更改中不作更改

view plaincopy to clipboardprint?
<property name="age" update="false"></property>
<property name="age" update="false"></property>

在Annotation中 在屬性GET方法上加上@Column(updatable=false)

view plaincopy to clipboardprint?
@Column(updatable=false) 
public int getAge() { 
return age; 
}
@Column(updatable=false)
public int getAge() {
return age;
}

咱們在執行 Update方法會發現,age 屬性 不會被更改

view plaincopy to clipboardprint?
Hibernate: 
update 
Teacher 
set 
birthday=?, 
name=?, 
title=? 
where 
id=?
Hibernate:
update
Teacher
set
birthday=?,
name=?,
title=?
where
id=?

缺點:不靈活&middot;&middot;&middot;&middot;

2.第2種方法&middot;&middot;使用XML中的 dynamic-update="true"

view plaincopy to clipboardprint?
<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語句修改數據

view plaincopy to clipboardprint?
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(); 
}
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語句:

view plaincopy to clipboardprint?
Hibernate: 
update 
Teacher 
set 
name='yangtianb' 
where 
id=3
Hibernate:
update
Teacher
set
name='yangtianb'
where
id=3

這樣就只更新了咱們更新的字段&middot;&middot;&middot;&middot;&middot;&middot;

相關文章
相關標籤/搜索