2

我正在尝试在 Micronaut Data JDBC 存储库中创建一个计数本机查询。我在用着:

@JdbcRepository(dialect = Dialect.POSTGRES)
public abstract class BookRepository implements GenericRepository<Book, Long> {
    @Transactional(Transactional.TxType.MANDATORY)
    @Query(value = "select count(*) FROM book WHERE registration_date > :date", nativeQuery = true)
    public abstract long countNow(@NotNull Timestamp date);
}

我得到以下编译错误:

error: Unable to implement Repository method: BookRepository.countNow(Timestamp date). Query results in a type [my.app.db.Book] whilst method returns an incompatible type: long

我该如何解决这个问题?

4

3 回答 3

1

我怀疑本机查询必须返回该存储库的实体。在您的情况下,它是Book.

但是您是否尝试过使用查询方法而不是自己编写查询。就像是

public abstract long countByRegistrationDateGreatherThan(Timestamp t);

有关详细说明,请参阅Micronaut Data 的文档。

于 2019-10-27T12:27:15.040 回答
0

这是一个例子CriteriaBuilder

val criteriaBuilder = entityManager.criteriaBuilder
val criteriaQuery = criteriaBuilder.createQuery(Long::class.java)
val root = criteriaQuery.from(EntityClass::class.java)
criteriaQuery.select(criteriaBuilder.count(root.get<Int>("id")))
于 2021-07-07T18:48:05.390 回答
0

这是 JdbcOperations 的另一个选项:

fun getCount(whereClause: String): Int {
    @Language("SQL")
    val sql = """SELECT COUNT(*) AS rowcount FROM book $whereClause"""
    return jdbcOperations.prepareStatement(sql) { statement ->
        val resultSet = statement.executeQuery()
        resultSet.next()
        resultSet.getInt("rowcount")
    }
}
于 2021-05-30T23:07:37.827 回答