如何在春季将表锁定为独占模式

时间:2015-07-15 20:17:59

标签: java sql spring postgresql spring-mvc

Noob春天的问题。如何在spring中运行下面的sql语句。到目前为止,我只使用了' NamedParameterJdbcTemplate'使用JDBC连接到postgresql数据库的类。

begin;
lock table tx_test_queue in exclusive mode;
update tx_test_queue
set status='running'
where
    job_id in (
        select job_id
        from tx_test_queue
        where status='queued'
        order by job_id asc
        limit 1 )
returning job_id;
commit;

这是我使用的Java代码无效。

private static final Logger logger = LoggerFactory.getLogger( BatchQueueDAO.class );

@Autowired
private NamedParameterJdbcTemplate template;

public BatchQueueBean getNextBatchJob() {
    MapSqlParameterSource params = new MapSqlParameterSource();

    StringBuilder sql = new StringBuilder();

    sql.append( "begin;" );
    sql.append( "lock table batch_queue in exclusive mode;" );
    sql.append( "update batch_queue set status_cd=2 where id in ( select id from batch_queue where status_cd=1 order by id asc limit 1) returning id;" );
    sql.append( "commit;" );

    SQLBuilderUtil.printMap( params, logger );

    List<BatchQueueBean> r = template.query( sql.toString(), new BeanPropertyRowMapper<>( BatchQueueBean.class ) );
    if( r.isEmpty() )
        return null;
    else
        return r.get( 0 );      
}

返回&#39;由以下原因引起:org.postgresql.util.PSQLException:查询&#39; 错误未返回任何结果。

1 个答案:

答案 0 :(得分:0)

@Query(value = "LOCK TABLE table_name IN EXCLUSIVE MODE", nativeQuery = true)
@Modifying
void lockTable();

来源: https://stackoverflow.com/a/65081097/2009145