开发者

Hibernate and "greatest value wins" logic

I have a high_scores table in my database, it has two values:

player_id
highest_score

I need a repository method that saves a new high score. I don't really want to dirty up my code with optimistic lock retry logic for something so simple. What I'd like executed is basically 开发者_如何学Gothis line:

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

That would mostly accomplish my goal just fine, although I'd also have to worry about creating a high score if the user didn't have one. I need to make sure that I never overwrite a high score with a lower score, but that's the only sort of locking this table needs.

Is there a way to ask hibernate to do something like this, or do I need to resort to custom SQL?


hibernate supports bulk update (from 3.3 on).

Edit:

Check: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct

Making it easier (from the Hibernate docs):

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();

cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜