在一个Hibernate查询中更新几个列?

时间:2012-09-06 09:00:10

标签: hibernate nhibernate hql

我有以下HQL:

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中做到这一点,但我不知道如何在Hibernate中做到这一点。

3 个答案:

答案 0 :(得分:27)

在这种情况下,HQL与SQL没有什么不同。只需使用逗号分隔列:

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

答案 1 :(得分: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);

答案 2 :(得分: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();