0

I know this isn't the best way to define a car class, but I got curious and I ended up writing this:

@Entity
@Table(name = "CAR")
public class Car {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String manufacturer;
    private String model;

    @ElementCollection
    @CollectionTable(
        name="ACCESSORY",
        joinColumns=@JoinColumn(name="OWNER_ID")
    )
    @Column(name="ACCESSORIES")
    private List<String> accessories;

    //getters and setters
}

and its repository

@Repository
public interface CarRepository extends JpaRepository<Car, Long> {   
}

Now, considering that I want to create a repository method that finds all the cars that meet a given list of accessories, how can I do it? I was thinking about a method like findById() or something. By the way, feel free if you want to answer in a way that "Accessories" is an entity.

Disclaimer: Yes, I tried the method List<Car> findByAccessoriesIn(List<String> as); but it brings any car that has at least one of the elements inside the list. I want all the cars that have all items inside the list.

1 Answers1

0

“finds all the cars that meet a given list of accessories“

If i understood correctly then - findByAccessoriesIn(List yourStrList) should work in this case.

A similar thread is here: Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For List in jpa we use “in” where “i” is in caps.

Ajay Kumar
  • 2,906
  • 3
  • 23
  • 46
  • Kind of. 'IN' clause brings any car that have at least one accessory. I want to bring only the cars that have all of the accessories inside the list. –  Apr 24 '21 at 20:30
  • Yeah pass those accessories string you want to find cars for. And I guess thats what you are looking for. Try it. – Ajay Kumar Apr 24 '21 at 20:32
  • It brings any car –  Apr 24 '21 at 20:57