首页 > 解决方案 > 如何在 Spring Boot JPA 中执行两个 SQL 查询

问题描述

我的 SQL 查询中有语法错误。这是我的查询:

@Transactional
    @Modifying
    @Query(value = "DELETE FROM Category WHERE id=:id \r\n"
            + "DELETE FROM Product_Category WHERE id=:id", nativeQuery = true)
    void deleteCategory(@Param("id") long id);

这是我的错误:

org.sqlite.SQLiteException:[SQLITE_ERROR] SQL 错误或缺少数据库(“,”附近:语法错误)

标签: sqlsqlitespring-bootspring-data-jpa

解决方案


我认为您不能通过在此处编写本机查询来直接实现此功能。您需要使用CustomRepositoryspring 提供的概念,并deleteCategory使用 entityManager 创建一个在其中触发两个查询的方法。然后您可以从您的服务层调用该方法。

假设您的存储库名称是CategoryRepository.

现在,首先您需要创建一个自定义存储库接口:

public interface CategoryRepositoryCustom {
    void deleteCategory(Long id);

}

然后写它的impl:

@Repository
@Transactional
public class CategoryRepositoryImpl implements CategoryRepositoryCustom {

    @PersistenceContext
    EntityManager em;

    @Override
    @Modifying
    public void deleteCategory(Long id) {
        //execute your two queries one by one using entity manager
    }
}

现在,您的主存储库CategoryRepository应该扩展两者JpaRepostory, 并且您可以从服务类CategoryRepositoryCustom调用该方法。deleteCategory有关自定义存储库的更多信息,请单击此处


推荐阅读