Hibernate NOWAIT不适用于SQL Server 2008

时间:2014-05-05 20:51:49

标签: java sql sql-server sql-server-2008 hibernate

我正在使用Hibernate 3.6.10FINAL,我无法为SQLServer2008生成nowait命令。我尝试过使用这两种方言(“SQLServer2008Dialect”和“SQLServerDialect”(它们都生成完全不同的SQL查询))无济于事。我尝试过以下方法:

List<TournamentTemplateRecord> leastRecentlyUsedTournaments = s.createCriteria(TournamentTemplateRecord.class)
            .addOrder(Order.asc("lastUse"))
            .setMaxResults(5)
            .setLockMode(LockMode.UPGRADE_NOWAIT)
            .setTimeout(0)
            .list();

List<TournamentTemplateRecord> leastRecentlyUsedTournaments = s.createQuery("from TournamentTemplateRecord ORDER BY lastUse")
    .setMaxResults(5)
    .setLockOptions(LockOptions.UPGRADE)
    .setTimeout(0)
    .list();

for(TournamentTemplateRecord t : leastRecentlyUsedTournaments){
        s.buildLockRequest(LockOptions.UPGRADE).setTimeOut(LockOptions.NO_WAIT).setLockMode(LockMode.UPGRADE_NOWAIT).lock(t);
    }

它们都不会生成nowait查询。这是所有情况下的生成查询:

WITH query AS (select
    ROW_NUMBER() OVER (
order by
    tournament0_.lastuse) as __hibernate_row_nr__,
    tournament0_.combattemplateid as id89_,
    tournament0_1_.combattypeid as combatty2_89_,
    tournament0_1_.combattargetid as combatta3_89_,
    tournament0_1_.resourcenameid as resource4_89_,
    tournament0_1_.resourcedescriptionid as resource5_89_,
    tournament0_1_.rewardloottemplateid as rewardlo6_89_,
    tournament0_1_.combatcontainertypeid as combatco7_89_,
    tournament0_.requirementtemplateid as requirem2_90_,
    tournament0_.assetid as assetid90_,
    tournament0_.durationinsec as duration4_90_,
    tournament0_.lastuse as lastuse90_ 
from
    tournament_tournamenttemplate tournament0_ 
inner join
    readyforcombat_combattemplate tournament0_1_ with (updlock, rowlock) 
        on tournament0_.combattemplateid=tournament0_1_.id ) SELECT
        * 
FROM
    query 
WHERE
    __hibernate_row_nr__ BETWEEN ? AND ?

如何让我的查询不等待锁定?

修改 值得一提的是,.setLockMode(LockMode.UPGRADE_NOWAIT).setLockMode(LockMode.PESSIMISTIC_WRITE)会生成完全相同的查询

更新 我发现这是我正在使用的hibernate版本中的一个问题。根据这个HHH-3961,这在我使用的Hibernate版本(3.6.10Final)中没有修复。升级Hibernate 4.x对我来说真的不是一个选项,有没有办法为我的查询手动设置“nowait”提示?

1 个答案:

答案 0 :(得分:2)

由于这个问题得到了一些赞成和观点,我以为我会发布我的解决方案。我最终做了一个原生查询。它并不理想,但它可以作为临时解决方法(即黑客)。

TournamentTemplateRecord lastActiveTournament = (TournamentTemplateRecord) s.createSQLQuery(
    "SELECT TOP 1 * FROM Tournament_TournamentTemplate tt " +
    "WITH (updlock, rowlock, nowait) " +
    "ORDER BY tt.lastUse desc"
)
    .addEntity(TournamentTemplateRecord.class)
    .uniqueResult();