Spring Data JPA:根据使用的 ManyToOne 字段过滤数据

Spring Data JPA: filter data based on used ManyToOne field

我有一个实体“Car”,其中“CarType”作为@ManyToOne @joinColumn 参数:

汽车实体:

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

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

  ...
}

CarType 实体:

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

CarType 存储库:

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

}

用户要求 CarTypes,我已经 api returns 所有 carTypes,但其中一些不再使用(没有现有汽车使用该 carTypes)

有什么方法可以使用 JpaRepository 仅检索“实际”使用过的 CarTypes 吗?

您必须编写自定义查询才能从数据库中获取实际使用的 CarTypes 数据。

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

这对我有用:

@Query (value = "SELECT DISTINCT t FROM Car c INNER JOIN CarType t ON p.carType.id = t.id WHERE t.deleted = false ORDER BY t.name ASC
List<CarType>findAllActiveCarTypes();