【问题标题】:Spring Data JPA: filter data based on used ManyToOne fieldSpring Data JPA:根据使用的 ManyToOne 字段过滤数据
【发布时间】:2021-11-16 08:05:10
【问题描述】:

我有一个实体“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,我已经有一个返回所有 carTypes 的 api,但是其中一些不再使用(没有现有的汽车使用 carType)

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

【问题讨论】:

  • 如何在代码中定义不再使用的 CarTypes?
  • @dope 没有现有汽车使用 carType
  • 您可以从数据库中的所有汽车中检索 distinct carType。
  • @ZakFST 你找到解决方案了吗?

标签: java sql spring-data-jpa spring-data


【解决方案1】:

这对我有用:

@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();

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2019-10-12
      • 2013-12-15
      • 2014-07-01
      • 2019-05-05
      • 2018-09-04
      • 1970-01-01
      相关资源
      最近更新 更多