[英]Generation query when the ManyToMany relationship is used by Spring Data Jpa project
I've the following entities mapping: 我有以下实体映射:
@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 is looked: 看了BookRepository接口:
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);
Please fix me if I'm wrong in the query itself. 如果我在查询本身错了,请修复我。 When I run test for the
findByCategories
method, I'm getting the error: 当我为
findByCategories
方法运行测试时,我收到错误:
testFindByCategories(com.savdev.springmvcexample.repository.JpaBookRepositoryTest): org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters.
testFindByCategories(com.savdev.springmvcexample.repository.JpaBookRepositoryTest):org.hibernate.QueryParameterException:超出声明的ordinal参数数量的位置。 Remember that ordinal parameters are 1-based!
请记住,序数参数是基于1的! Position: 1;
位置:1; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: Position beyond number of declared ordinal parameters.
嵌套异常是java.lang.IllegalArgumentException:org.hibernate.QueryParameterException:超出声明的ordinal参数数量的位置。 Remember that ordinal parameters are 1-based!
请记住,序数参数是基于1的! Position: 1
职位:1
Which option do I have to resolve it? 我有哪个选项可以解决它?
And the second, can I debug Spring Data Jpa logic that passes the argument into the query? 第二,我可以调试将参数传递给查询的Spring Data Jpa逻辑吗? I'm getting a proxy returned by Spring Data Jpa, cannot understand where to use break point to debug this behaviour.
我得到了Spring Data Jpa返回的代理,无法理解在哪里使用断点来调试这种行为。
UPDATE: I've fixed it by using (?1)
: 更新:我用
(?1)
修复了它:
@Query("SELECT b FROM Book b INNER JOIN b.categories c WHERE c IN (?1)")
instead of 代替
@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. 由于参数名称在字节码中丢失,因此您需要使用@Param注释来指示在JPQL中映射为
:category
变量的参数。 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
certainly works, but is probably not as readable. ?1
肯定有效,但可能不那么可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.