【问题标题】:Spring boot using foreign key in crudRepository在 crudRepository 中使用外键进行 Spring Boot
【发布时间】:2017-11-17 21:41:24
【问题描述】:

我有 3 个实体

  • CarWashWash设置)
  • Wash (car_wash_id FK to CarWash)
  • WashComment(wash_id FK 转 Wash)

有没有办法写这个查询

   @Query(value="select * from wash_comment where wash_comment.wash_id=(select wash_id from wash where wash.car_wash_id=2", nativeQuery=true))
List<WashComment> findAllByCarWashId(CarWash carWash)

不使用 nativeQuery?

【问题讨论】:

    标签: spring-boot spring-data-jpa


    【解决方案1】:

    处理 JPA 的建议:远离表、列和您拥有的所有 RDBMS 对象,而专注于实体、它们的属性和关系。

    如果我正确理解了你的问题,你可以让 Spring Boot 自动解决它,使用

    List<WashComment> findByWash_CarWash_Id($Parameter(name="id") int id) 
    

    方法签名 - 其中_ 具有. 之间的含义及其属性,遍历点 - 指定基于wash.carWash.id 的查找。所以这将转化为这样的东西:

    select * 
    from WashComment wc
    where wc.wash.carWash.id=:id
    

    (当然,将其放入@Query 注释中是完全有效的)

    假设您的 WashComment 和 Wash 对象如下所示:

    public class WashComment {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private long id;
    
      @OneToMany
      private Wash wash;
    
      //... left out for brevity
    }
    
    public class Wash {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private long id;
    
      @OneToMany
      private CarWash carWash;
    
      //... left out for brevity
    }
    

    Wash 类的@Id 字段被命名为id

    关于这种表达的更多信息在这里:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions

    建议 2:如果您需要使用内部选择 - 尝试使用 JOIN 重写它。 100 次中有 99 次,这将是可能的,而且可读性更高,通常性能也更高:

    select wc.* 
    from wash_comment wc
    join wash w on wc.wash_id=w.wash_id
    where wash.car_wash_id=2
    

    (免责声明:我现在不能尝试任何这些,附近没有 JRE 可以玩......)

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2016-02-12
      • 2018-10-02
      • 2020-11-15
      相关资源
      最近更新 更多