Hibernate之update(1)——更新部分欄位

來源:互聯網
上載者:User

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.