2012-09-06 64 views
9

我有以下HQL:在一個Hibernate查詢中更新幾個列?

String hql = "UPDATE Buchung as b " + 
      "set STORNO = :Storno " + 
      "where ID = :BuchungID"; 

是否有可能更新一個以上的列在HQL?例如:

String hql = "UPDATE Buchung as b " + 
       "set STORNO = :Storno " + 
       "set NAME = :Name " + 
       ...... 
       "where ID = :BuchungID"; 

我知道如何做到這一點在MSSQL中,但我不知道如何做到這一點在休眠。

回答

22

在這種情況下,HQL與SQL沒有區別。只要用逗號分隔列:

String hql = "UPDATE Buchung as b set " + 
      "STORNO = :Storno," + 
      "NAME = :Name " + 
      ...... 
      "where ID = :BuchungID"; 
+0

感謝工作像魅力! – Paks

2

的語法類似於SQL的語法,但映射的字段/屬性而不是列:

update Buchung set storNo = :storno, name = :name where id = :buchungID 

注意,如果目的是修改單實體實例,你最好做

Buchung b = (Buchung) session.get(Buchung.class, buchungId); 
b.setStorNo(newStorno); 
b.setName(newName); 
+0

也感謝您的幫助! – Paks

+0

@JB Nizet如何處理這種情況'更新employee set empName =:empname,address =:address where dept =:dept'。我沒有根據id更新。 –

+0

然後更新查詢更有效。雖然你可以使用select查詢加載所有匹配的實體,然後在循環中更新它們。請注意,直接更新查詢會繞過第一級緩存。 –

1
String hql = "UPDATE Buchung as b set " + 
      "STORNO = :Storno," + 
      "NAME = :Name " + 
      ...... 
      "where ID = :BuchungID"; 

Query qr = session.createSQLQuery(hql); 

qr.setParameter("Storno","sto_value"); 

qr.setParameter("Name","name_value"); 

... 

qr.executeUpdate(); 
正常

,你必須有「交易」運行查詢

Transaction transaction = null; 
transaction = session.begintransaction(); 
... 
transaction.commit();