问题描述
我具有以下实体映射:
@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:
我必须解决哪个选项?
第二,我可以调试将参数传递给查询的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)")
推荐答案
由于参数名称丢失了字节码,因此您需要使用 @ Param 注释以指示映射为:category
变量的参数在您的JPQL中.因此,您的代码将如下所示:
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关系时的生成查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!