![](/img/trans.png)
[英]How do I write a query with LIKE against a column with Spring Data?
[英]How can I write spring data query with IN statement?
我需要通过Entity2的ID来获取Entity1
查询有参数-列表编号-实体2的ID。 和两个具有@OneToMany绑定的实体
@Entity
class Entity1 {
private Integer id;
private Entity2 entity2;
---------
@OneToMany(cascade = ALL, fetch =FetchType.EAGER)
@Column
public Entity2 getEntity2(){
return entity2;
}
和
@Entity
public class Entity2{
private Integer id;
@ManyToOne(FetchType.LAZY)
private Entity1 entity1;
}
我有工作代码
@Repository
public interface Entity1Repository extends JpaRepository<Entity1, Integer> {
@Query("SELECT c" +
" FROM Entity1 c" +
" inner JOIN c.entity2 a" +
" WHERE a.id IN(?1)")
Set<Entity1> findByEntity2Ids(List<Integer> pEntity2_Ids);
}
我想通过使用Spring Data美化查询
并写一些像
Set<Entity1> findAllByEntity2In(List<Integer> pChannels);
但现在不起作用
我陷入了困惑:
\\原因:java.lang.IllegalArgumentException:参数值元素[2]与预期的类型[com.test.Entity2(n / a)]不匹配
谁知道如何解决?
谢谢 !
UPD
我发现了对Spring Data的查询:
@Repository
public interface Entity1Repository extends JpaRepository<Entity1, Integer> {
Set<Enity1> findByEntity2In(List<Integer> pEntities2Ids);
}
从查询中删除括号。 它看起来应该像这样:
@Query("SELECT c" +
" FROM Entity1 c" +
" inner JOIN c.entity2 a" +
" WHERE a.id IN ?1")
为了使查询更易读,您可以选择使用命名参数而不是位置参数。 这样说,您的查询可能是这样的:
@Query("SELECT c" +
" FROM Entity1 c" +
" inner JOIN c.entity2 a" +
" WHERE a.id IN :ids")
Set<Entity1> findByEntity2Ids(@Param("ids") List<Integer> pEntity2_Ids);
您可以按列表或Entity2的集合进行搜索,例如
Set<Entity1> findByEntity2In(Set<Entity2> entity2);
为了通过Entity2 Id查找,您需要编写如下查询
@Query("SELECT ent1 FROM Entity1 ent1 INNER JOIN c.entity2 ent2 WHERE ent2.id IN :ids")
Set<Entity1> findByEntity2Ids(@Param("ids") List<Integer> pEntity2_Ids);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.