如何在Spring Boot CrudRepository中搜索数组 [英] How to search through array in Spring Boot CrudRepository

查看:138
本文介绍了如何在Spring Boot CrudRepository中搜索数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有以下实体类:

Person.java

@Entity
public class Person {
  @Id
  private String name;

  private String[] cars;

  // Constructor, getters and setters
}

还有存储库:

PersonRepository.java

public interface PersonRepository extends CrudRepository<Person, String> {

   // this is unclear!
   List<Person> getAllByCars...(String car)
}

有没有一种方法可以返回所有人,他们的汽车数组包含一辆给定的汽车(上面的String参数)?

Is there a method that returns all persons, whose car array contains one given car (the String parameter above)?

对我来说,似乎所有受支持的JPA关键字只能处理单个元素,而不能处理数组.

For me, it seems that all supported JPA keywords can only deal with single elements, but not with arrays.

感谢帮助!

推荐答案

理想情况下,您应该像这样将汽车声明为单独的实体

Ideally, You should declare cars as a separate Entity like this

@Entity
public class Person {
  @Id
  private String name;

  private List<Car> cars;

  // Constructor, getters and setters
}

否则,至少应将数组"更改为列表". 更改

If not you should change Array to List at the least. change

private String[] cars;

@ElementCollection
private List<String> cars;

然后您必须编写这样的查询

Then You have to write a Query like this

@Query("select p from Person p WHERE :car in elements(p.cars)")
List<Person> getAllByCars...(@Param("car") String car)

这篇关于如何在Spring Boot CrudRepository中搜索数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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