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

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

问题描述

比如说,我有以下实体类:

Say, I have the following entity 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)
}

是否有一种方法可以返回所有人员,其汽车数组包含一个给定的汽车(上面的 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
}

如果不是,您至少应该将 Array 更改为 List.改变

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天全站免登陆