计数器使用Spring的JPA存储库

时间:2016-09-09 14:16:27

标签: java mysql jpa spring-data spring-data-jpa

我很确定这是一种常见的情况 - 我有一个表格,其中列作为计数器。我需要递增值并需要知道递增的值。

我可以使用Spring的JPA存储库执行类似的操作:

@Transactional
public getNextValue(){
    DataPO po = repository.find("someId");
    po.setCounter(po.getCounter+1);
    repository.save(po);
}

它的缺点是使用锁定,因此很慢。

我读到使用 last_insert_id 的方法来有效地执行此操作但我找到的示例不使用存储库,他们直接使用 EntityManager sample

这是来自链接页面:

Query query = entityManager.createNativeQuery("UPDATE counter SET value = LAST_INSERT_ID(value + 1) WHERE name = :name");
query.setParameter("name", client.getName());
query.executeUpdate();

query = entityManager.createNativeQuery("SELECT LAST_INSERT_ID()");
long value = ((BigInteger) query.getSingleResult()).longValue();
value = value - 1;

有没有办法用Spring的JPA存储库来做到这一点?我在文档中找不到任何内容:Spring's JPA Repositories

我可以使用JPA存储库进行其他有效的方法吗?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用Spring Data JPA中的Native Queries

在您的情况下:

public interface CounterRepository extends JpaRepository<Counter, Long>{

    @Modifying
    @Query(value = "UPDATE Counter SET value = LAST_INSERT_ID(value + 1) WHERE name = ?1", nativeQuery = true)
    int updateCounterByName(String name);

    @Query(value = "SELECT LAST_INSERT_ID()", nativeQuery = true)
    int getLastInsertId();

    Counter findOneByName(String name);

}

检查我的GitHub存储库中的Complete Project