gpt4 book ai didi

java - Spring Data Jpa项目使用ManyToMany关系时的生成查询

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:06 25 4
gpt4 key购买 nike

我有以下实体映射:

@Entity
@Table(name = "books")
public class Book implements Serializable {
@ManyToMany
@JoinTable(name="books2categories",
joinColumns=@JoinColumn(name="book_id"),
inverseJoinColumns=@JoinColumn(name="category_id"))
Collection<Category> categories;

...

@Entity
@Table(name = "categories")
public class Category implements Serializable {
@ManyToMany(mappedBy="categories")
private Collection<Book> books;

BookRepository接口(interface)看:

public interface BookRepository extends JpaRepository<Book, Long> {

@Query("SELECT b FROM Book b INNER JOIN b.categories c WHERE c IN (:categories)")
List<Book> findByCategories(Collection<Category> categories);

如果我的查询本身有误,请修复我。当我为 findByCategories 方法运行测试时,出现错误:

testFindByCategories(com.savdev.springmvcexample.repository.JpaBookRepositoryTest): org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters. Remember that ordinal parameters are 1-based! Position: 1

我必须选择哪个选项来解决它?

第二,我可以调试将参数传递到查询中的 Spring Data Jpa 逻辑吗?我收到 Spring Data Jpa 返回的代理,无法理解在何处使用断点来调试此行为。

更新:我已经使用 (?1) 修复了它:

@Query("SELECT b FROM Book b INNER JOIN b.categories c WHERE c IN (?1)")

代替

@Query("SELECT b FROM Book b INNER JOIN b.categories c WHERE c IN (:categories)")

最佳答案

由于参数名称在字节码中丢失,您需要使用 @Param注释以指示映射为 JPQL 中的 :category 变量的参数。所以,你的代码看起来像:

@Query("SELECT b FROM Book b INNER JOIN b.categories c WHERE c IN (:categories)")
List<Book> findByCategories(@Param("categories") Collection<Category> categories);

?1 当然可以,但可能不那么可读。

关于java - Spring Data Jpa项目使用ManyToMany关系时的生成查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com