java 如何通过 HibernateTemplate 更新数据库中的特定字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13374223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:29:16  来源:igfitidea点击:

How can I update specific field in database by HibernateTemplate

javasqlhibernateexceptionsql-update

提问by SRy

I want to update a specific field in the database Personstable by using HibernateTemplate. I am trying to do like this but this not working.

我想Persons使用 HibernateTemplate更新数据库表中的特定字段。我正在尝试这样做,但这不起作用。

public void  updateDate(int Id,Date receivedDate) {
      Id = 10;
      receivedDate = 2012-11-12;
      String queryString = "update Persons set recievedDate=? where Id=? ";
      getHibernateTemplate().update(queryString, new Object[] { Id, receivedDate });
}

I am getting an exception "UnkownEntity" when I run this query. Can I do update of a specific field at all by using HibernateTemplate? Is there any other alternate to do specific field update?

运行此查询时出现异常“UnkownEntity”。我可以使用 HibernateTemplate 更新特定字段吗?是否有其他替代方法可以进行特定字段更新?

回答by Sajan Chandran

updatemethod in getHibernateTemplatedoes not allow hql query to execute. It only allows hibernate entity object.

update方法 ingetHibernateTemplate不允许执行 hql 查询。它只允许休眠实体对象。

See link hibernate template update method

见链接休眠模板更新方法

In your case Hibernate tries to resolve update Persons set recievedDate=? where Id=?as an entity.

在您的情况下,Hibernate 尝试解析update Persons set recievedDate=? where Id=?为一个实体。

Solution:

解决方案:

Query q = s.createQuery("update Persons set recievedDate=:recievedDate where Id=:Id");
q.setString("recievedDate", "some date");
q.setString("Id", "54");
q.executeUpdate();

Hope its clear.

希望它清楚。

回答by Konstantin Kudryavtsev

You have to list your classes in your session factory configuration.

您必须在会话工厂配置中列出您的类。

回答by Konstantin Kudryavtsev

I assume your entity named Person in HQL you must use java class name, not db table name

我假设您在 HQL 中名为 Person 的实体必须使用 java 类名,而不是 db 表名

回答by Bhaskar P

if HibernateTemplate is using, here is my solution.

如果正在使用 HibernateTemplate,这是我的解决方案。

// EntityName is the table to be updated

EntityName entity =  hibernateTemplate.find("from EntityName where id=?" , id);

//set the value which has to be updated

entity.setValue(yourNewValue);

hibernateTemplate.SaveOrUpdate(entity);  

// above updated the existing Entity table without duplicates