Update several Columns in one Hibernate Query?

北慕城南 提交于 2020-01-01 08:02:54

问题


i have the Following HQL:

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

Is it possible to Update more then one column in a HQL? For Example:

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

I know how to do that in MSSQL but i dont know how to do that in Hibernate.


回答1:


HQL is no different than SQL in this case. Just use comma to separate columns:

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



回答2:


The syntax is similar to the SQL syntax, but with mapped fields/properties instead of columns:

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

Note that if the goal is to modify a single entity instance, you'd better do

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



回答3:


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

in normal, you must have "transaction" to run query

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


来源:https://stackoverflow.com/questions/12296499/update-several-columns-in-one-hibernate-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!