How to search through array in Spring Boot CrudRepository

后端 未结 2 2015
我寻月下人不归
我寻月下人不归 2021-01-06 18:43

Say, I have the following entity class:

Person.java

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

  private String[] c         


        
相关标签:
2条回答
  • 2021-01-06 19:02

    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;
    

    to

    @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)
    
    0 讨论(0)
  • 2021-01-06 19:20

    I'm guessing at how you are currently storing the cars information and suggesting a possible solution:

    @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);
    }
    
    0 讨论(0)
提交回复
热议问题