首页 > 解决方案 > 如何在 postgres 和 Hibernate/Spring 中使用 LIMIT 子句

问题描述

我有这个在我的 DAO 中不起作用的本机查询

@Query(
            nativeQuery = true,
            value = "DELETE FROM products_in_carts WHERE cart_id =?1 AND product_name = ?2 LIMIT= 1"
    )
    void removeProduct(long id, String productName);

返回:org.postgresql.util.PSQLException: ERROR: syntax error at or near "LIMIT"

我按照其他一些问题的建议尝试过,OFFSET但也不起作用

标签: javaspringhibernatespring-data-jpaspring-rest

解决方案


那是因为,据我正确理解文档,postgres 不支持使用LIMITindelete语句。因此,您可以尝试使用解决方法来满足您的要求。例如,通过在 delete 语句中使用子查询来获取要删除的行。由于我不知道您的表格设计,我正在使用CTIDpostgres 的此处来识别要删除的行。

取自文档(https://www.postgresql.org/docs/8.2/ddl-system-columns.html

ctid 行版本在其表中的物理位置。请注意,虽然 ctid 可用于非常快速地定位行版本,但行的 ctid 会在每次更新或被 VACUUM FULL 移动时发生变化。因此 ctid 作为长期行标识符是无用的。OID,或者更好的用户定义的序列号,应该用于识别逻辑行。

例如(未测试):

@Query(
        nativeQuery = true,
        value = "DELETE FROM products_in_carts WHERE ctid in (select ctid from product cart_id =?1 AND product_name = ?2 LIMIT= 1)"
)
void removeProduct(long id, String productName);

推荐阅读