1

I would like to update column value with a new entity value incrementally, for example:

support I have a table USER with COLUMN name BALANCE

for specific user, his balance is 3000.

Now, I would like to set his value to 3500.

I have hibernate "User" Entity that has a 'balance' value of 500.

How can I make the update??

If I would like to make it using pure sql query, I would simple do:

"UPDATE USER set balance = balance+500 where user_id=3"

I would like to avoid calling sql and use hibernate.

4

3 に答える 3

4

以下のコードを試しましたか?質問をする前に、あなたが試した可能性のあるすべての解決策について言及することを常に忘れないでください.

User user=session.get(User.class, 3); // 3 is ID of user. 
user.setBalance((user.getBalance()+500));
session.saveOrUpdate(user);
session.commit();
于 2013-04-25T11:00:44.427 に答える
1

これはあなたのために働くはずです:

Query query = session.createQuery("UPDATE User u SET u.balance = :balance WHERE u.id = :userId");
query.setParameter("balance", balance + 500);
query.setParameter("userId", 3);
query.executeUpdate();

SQL のようにテーブルを更新するのUserではなく、HQL を介してエンティティを更新していることに注意してください。また、と の列がエンティティのと の属性にマップされているとUSER仮定しました。balanceidbalanceidUser

于 2013-04-25T09:41:28.457 に答える