如何在 Spring Boot CrudRepository 中搜索数组
How to search through array in Spring Boot CrudRepository
说,我有以下实体 class:
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)
}
有没有一种方法 returns 所有人,其汽车数组包含一辆给定的汽车(上面的 String 参数)?
对我来说,似乎所有支持的JPA关键字都只能处理单个元素,而不能处理数组。
感谢帮助!
我在猜测你目前是如何存储汽车信息的,并提出了一个可能的解决方案:
@Entity
public class Car {
@Id
private String name;
@Column
private String person_name;
}
public interface CarRepository extends JpaRepository<Car, String> {
//Result will have all cars with the person_name identifying the Person @Entity
List<Car> findByName(String name);
}
理想情况下,您应该像这样将汽车声明为单独的实体
@Entity
public class Person {
@Id
private String name;
private List<Car> cars;
// Constructor, getters and setters
}
否则,您至少应该将 Array 更改为 List。
改变
private String[] cars;
到
@ElementCollection
private List<String> cars;
然后你必须像这样写一个查询
@Query("select p from Person p WHERE :car in elements(p.cars)")
List<Person> getAllByCars...(@Param("car") String car)
说,我有以下实体 class:
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)
}
有没有一种方法 returns 所有人,其汽车数组包含一辆给定的汽车(上面的 String 参数)?
对我来说,似乎所有支持的JPA关键字都只能处理单个元素,而不能处理数组。
感谢帮助!
我在猜测你目前是如何存储汽车信息的,并提出了一个可能的解决方案:
@Entity
public class Car {
@Id
private String name;
@Column
private String person_name;
}
public interface CarRepository extends JpaRepository<Car, String> {
//Result will have all cars with the person_name identifying the Person @Entity
List<Car> findByName(String name);
}
理想情况下,您应该像这样将汽车声明为单独的实体
@Entity
public class Person {
@Id
private String name;
private List<Car> cars;
// Constructor, getters and setters
}
否则,您至少应该将 Array 更改为 List。 改变
private String[] cars;
到
@ElementCollection
private List<String> cars;
然后你必须像这样写一个查询
@Query("select p from Person p WHERE :car in elements(p.cars)")
List<Person> getAllByCars...(@Param("car") String car)