Spring Boot 在 crudRepository 中使用外键

Alm*_*zak 6 spring-data-jpa spring-boot

我有 3 个实体

  • CarWashWash套)
  • Wash( car_wash_idFK 到CarWash)
  • WashComment( wash_idFK 到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)
Run Code Online (Sandbox Code Playgroud)

不使用 nativeQuery?

ppe*_*rka 12

处理 JPA 的建议:将目光从表、列和您拥有的所有 RDBMS 对象上移开,而将注意力集中在实体、它们的属性和关系上。

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

List<WashComment> findByWash_CarWash_Id($Parameter(name="id") int id) 
Run Code Online (Sandbox Code Playgroud)

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

select * 
from WashComment wc
where wc.wash.carWash.id=:id
Run Code Online (Sandbox Code Playgroud)

(当然,将其放入@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
}
Run Code Online (Sandbox Code Playgroud)

并且该类的@Id字段Wash名为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
Run Code Online (Sandbox Code Playgroud)

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