2012-11-14 28 views
2

我想通過使用HibernateTemplate來更新數據庫Persons表中的特定字段。我正在嘗試這樣做,但這不起作用。如何更新HibernateTemplate數據庫中的特定字段

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當我運行此我query.Can做一個特定領域的更新,在所有使用的HibernateTemplate?有沒有其他備選方案可以進行特殊字段更新?

+0

請問您可以使用實體人的代碼。 – OQJF

回答

3

update方法不允許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(); 

希望其明確的。

+0

非常感謝。它完全爲我工作。你爲我節省了很多時間。 – SRy

+0

_請注意:_實際上你仍然可以**使用['bulkUpdate(String queryString)'](https://docs.spring.io/spring/docs/2.0.x/javadoc-api/index。 html?org/springframework/orm/hibernate3/HibernateTemplate.html)執行以Hibernate的查詢語言**表示的查詢。 – informatik01

0

你必須在你的會話工廠配置中列出你的類。

+0

我已經這樣做了。上述同一個人對象正在爲其他查詢工作。是否我的查詢有問題? – SRy

0

我假設你在HQL名爲Person 必須使用Java類名稱的實體,而不是分貝getHibernateTemplate表名

-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 
相關問題