0

データベースにhigh_scoresテーブルがあり、2つの値があります。

player_id
highest_score

新しいハイスコアを保存するリポジトリメソッドが必要です。非常に単純なもののために、楽観的なロック再試行ロジックでコードを汚したくありません。私が実行したいのは基本的にこの行です:

update high_scores
set highest_score = :new_high_score
where player_id = :player_id
and highest_score <= :new_high_score

これでほとんどの場合、私の目標は問題なく達成されますが、ユーザーがハイスコアを持っていない場合は、ハイスコアを作成することについても心配する必要があります。高いスコアを低いスコアで上書きしないようにする必要がありますが、このテーブルに必要なロックはそれだけです。

hibernateにこのようなことをするように依頼する方法はありますか、それともカスタムSQLに頼る必要がありますか?

4

1 に答える 1

2

hibernateは一括更新をサポートします(3.3以降)。

編集:

チェック: http ://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct

簡単にする(Hibernateドキュメントから):

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
        .setString( "newName", newName )
        .setString( "oldName", oldName )
        .executeUpdate();
tx.commit();
session.close();

乾杯!

于 2011-04-29T17:32:46.507 に答える