【问题标题】:How execute two SQL query in the Spring Boot JPA如何在 Spring Boot JPA 中执行两个 SQL 查询
【发布时间】:2019-07-18 16:48:53
【问题描述】:

我的 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 错误或缺失 数据库(“,”附近:语法错误)

【问题讨论】:

    标签: sql sqlite spring-boot spring-data-jpa


    【解决方案1】:

    我认为您不能通过在此处编写本机查询来直接实现此功能。 您需要使用 spring 提供的 CustomRepository 概念并创建一个方法 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 应该同时扩展 JpaRepostoryCategoryRepositoryCustom,您可以从服务类调用deleteCategory 方法。 更多关于自定义仓库here

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2019-07-14
      • 1970-01-01
      • 2022-09-22
      相关资源
      最近更新 更多