A表
和 B表
是一对多关系
class A {
Long id;
}
class B {
Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn("aid")
A a;
}
在 BRepository
中创建命名查询 List<B> findByAId(Long aid)
生成的 SQL
是:
select b.* from b left outer join a on b.aid = a.id where a.id = ?
有没有办法让它不关联A表,直接使用 from b where aid = ?
作为条件。
JPQL
生成的 SQL
倒是可以解决上面的问题,但是每个简单的查询都要写遍 JPQL
又太麻烦了。
@Query("select b from B b where b.a.id = :aid")
List<B> findByAId(Long aid)
生成的 SQL
是:
select * from b where aid = ?
可以直接写啊,你这个查询里又没有来自 a 表的字段,直接用
所谓外键,只是在 insert 和 update 时有限制,跟 select 无关的。