如何使用hibernate更新java中的表而不使用hql和sql

use*_*372 11 java hibernate hql

我已经尝试了很多使用hql更新我的表但我没有找到解决方案,我也在互联网上搜索过,我是java和hibernate的新手请帮我找到解决方案.

我的代码写在下面.

session.getTransaction().begin();
Query query = session.createQuery("update DocDetail set DocName = :docname" + 
    " where Id = :docId");
query.setParameter("docname", "Jack");
query.setParameter("docId", 3);
int result = query.executeUpdate();
session.getTransaction().commit();
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误.

Exception in thread "AWT-EventQueue-0" org.hibernate.QueryException: query must begin with SELECT or FROM: update [update clinic.entity.DocDetail set DocName = :studentName where Id = :studentId]
at org.hibernate.hql.classic.ClauseParser.token(ClauseParser.java:106)
at org.hibernate.hql.classic.PreprocessingParser.token(PreprocessingParser.java:131)
at org.hibernate.hql.classic.ParserHelper.parse(ParserHelper.java:51)
Run Code Online (Sandbox Code Playgroud)

fai*_*gat 18

如果您正在使用休眠,则应尝试访问实体而不是表.
hibernate的最大优点是它为您提供了ORM(对象关系映射).
下面是如何使用hibernate更新实体的示例
(当然相应的表也会更新).

/* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                    (Employee)session.get(Employee.class, EmployeeID); 
         employee.setSalary( salary );
         session.update(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
Run Code Online (Sandbox Code Playgroud)

  • 通常你在交易边界做更新.但是您可以删除与交易相关的代码.如果你确定你不需要它. (2认同)

Ash*_*tap 14

您正在使用createQuery()方法而不是createSQLQuery()方法创建本机(SQL)查询,因此只需更改您的代码,如下所示

session.getTransaction().begin();
Query query = session.createSQLQuery(
    "update DocDetail set DocName = :docname" + " where Id = :docId");
query.setParameter("docname", "Jack");
query.setParameter("docId", 3);
int result = query.executeUpdate();
session.getTransaction().commit();
Run Code Online (Sandbox Code Playgroud)

详细了解这个:


Div*_*ers 5

__CODE__用于选择,因为您可以从异常中读取.要更新没有SQL或HQL的对象,可以使用下一个代码段.

 Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     sess.update(yourObject);
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }
Run Code Online (Sandbox Code Playgroud)

阅读有关更新的文档- 您可能必须使用mergesaveOrUpdate.

  • `createQuery`用于创建查询.它被称为`executeUpdate`是有原因的. (2认同)
  • 错误,createQuery不仅用于选择。您也可以执行更新和删除。在SQL行话中,任何DML操作都是查询。 (2认同)