Zak FST
Zak FST

Reputation: 371

Spring Data JPA: filter data based on used ManyToOne field

I have an entity "Car" with "CarType" as @ManyToOne @joinColumn parameter:

Car entity:

@Entity
public class Car implements serializable {
  @Id
  private Long id;

  @ManyToOne(targetEntity = CarType.class)
  private CarType carType;

  ...
}

CarType entity:

@Entity
public class CarType implements serializable {
  @Id
  private Long id;
  private String name;
  private String version;
  
  ...
}

CarType repository:

@Repository
public interface CarType extends JpaRepository<CarType, Long> {
   List<CarType> findAllOrderByNameAsc();

}

Users ask for CarTypes, I have already an api that returns all carTypes, but some of them are no longer used (no existing car uses the carType)

is there any way to retrieve only "actual" used CarTypes using JpaRepository ?

Upvotes: 2

Views: 588

Answers (1)

dope
dope

Reputation: 315

You have to write a custom query to get the actually used CarTypes data from the database.

@Query(
  value = "SELECT * FROM cartype t2 WHERE EXISTS (SELECT * FROM car as t1 WHERE t1.cartype = t2.id)", 
  nativeQuery = true)
List<CarTypes> findAllActiveCarTypes();

Upvotes: 2

Related Questions