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

时间:2012-11-14 06:48:13

标签: java sql hibernate exception sql-update

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

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

当我运行此查询时,我得到UnkownEntity Exception。我可以使用HibernateTemplate来更新特定字段吗?还有其他替代方法可以进行Speicific字段更新吗?

4 个答案:

答案 0 :(得分:3)

update中的

getHibernateTemplate方法不允许执行hql查询。它只允许hibernate实体对象。

请参阅链接hibernate template update method

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

<强>解决方案:

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

希望清楚。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

答案 3 :(得分:-2)

如果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