3

Say, I have the following entity class:

Person.java

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

  private String[] cars;

  // Constructor, getters and setters
}

And the repository:

PersonRepository.java

public interface PersonRepository extends CrudRepository<Person, String> {

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

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

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

Thanks for help!

user7346048
  • 798
  • 1
  • 9
  • 15

2 Answers2

5

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)
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • Thanks for your answer! Your suggested query did the trick. Since I'm using only a list of Strings in this example, I don't see a reason to implement a separate entity for that – user7346048 Jan 24 '18 at 16:31
  • 1
    b.t.w. I had to annotate cars with @ElementCollection in order to make it work – user7346048 Jan 24 '18 at 16:36
  • sorry forgot to mention that. Updated the answer – pvpkiran Jan 24 '18 at 16:38
  • After changing String[] to List, you could just define a method in your CrudRepository like this and that would do the job ---- List findAllByCars(String car) – abhaybhatia Sep 05 '19 at 23:32
0

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);
}
DaShaun
  • 3,722
  • 2
  • 27
  • 29