处理 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 可以玩......)