Spring Data Jpa项目使用ManyToMany关系时的生成查询 [英] Generation query when the ManyToMany relationship is used by Spring Data Jpa project

查看:423
本文介绍了Spring Data Jpa项目使用ManyToMany关系时的生成查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下实体映射:

@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界面被查看:

BookRepository interface is looked:

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方法时,出现错误:

Please fix me if I'm wrong in the query itself. When I run test for the findByCategories method, I'm getting the error:

testFindByCategories(com.savdev.springmvcexample.repository.JpaBookRepositoryTest): org.hibernate.QueryParameterException:位置超出 声明的序数参数.请记住,序数参数是 从1开始!位置:1;嵌套的例外是 java.lang.IllegalArgumentException: org.hibernate.QueryParameterException:位置超出 声明的序数参数.请记住,序数参数是 从1开始!位置:1

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返回的代理,无法理解在何处使用断点来调试此行为.

And the second, can I debug Spring Data Jpa logic that passes the argument into the query? I'm getting a proxy returned by Spring Data Jpa, cannot understand where to use break point to debug this behaviour.

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

UPDATE: I've fixed it by using (?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)")

推荐答案

由于参数名称丢失了字节码,因此您需要使用

Since parameter names are lost in bytecode, you need to use @Param annotation to indicate the parameter that is mapped as the :category variable in your JPQL. So, you code would look like:

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

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

?1 certainly works, but is probably not as readable.

这篇关于Spring Data Jpa项目使用ManyToMany关系时的生成查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆