sql - 如何在 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 错误或缺少数据库(“,”附近:语法错误)
解决方案
我认为您不能通过在此处编写本机查询来直接实现此功能。您需要使用CustomRepository
spring 提供的概念,并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
有关自定义存储库的更多信息,请单击此处
推荐阅读
- postgresql - docker run 命令中的 -d2 标志是什么
- node.js - 带有 kubernetes 和微服务的 nodejs 上的 socket.io 问题
- javascript - Js 返回 0 而不是值
- javascript - 我怎样才能取消我刮掉的一些CSS?
- javascript - Javascript EventListener 和 Element Selector 问题
- python - 如何将 bs4 findall() 对象转换为字符串
- python - 将批处理输入与 tf.math.invert_permutation 一起使用
- android - Listview.builder 将一个小部件定位在另一个小部件上
- javascript - !fullResponse?.response?.is_complete 没有按预期行事
- node.js - Node.JS - 一个返回用户是否存在或不从 mysql db 查询的函数