【发布时间】:2021-07-18 02:05:34
【问题描述】:
我正在使用带有 JPA 2.0 的 SpringBoot 2.4,并且我有一个如下模型:
@Entity
@Data
public class Nation {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy = "nation")
private List<Country> country;
}
还有:
@Entity
@Data
public class Country {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Nation nation;
}
现在我想找到所有Nation 过滤的ID 和country ID。纯粹的SQL 就是这样的:
select * from nation n, country c where n.id = [nation_id] AND c.id = [country_id];
因此我想用 JPA 来做这种方式:
@Query("select n from Nation n JOIN n.country c where n.id = ?1 AND c.id = ?2)
public List<Nation> find(Integer nationID, Integer countryID);
但它不起作用;它按国家过滤,但不按国家/地区过滤。
如果我打印 Hibernate 通过添加生成 SQL:
spring.jpa.show.sql=true
我可以看到查询与我上面在纯 SQL 中发布的完全一样。当我调用nation.getCountry() 时出现问题,它会生成另一个查询,该查询会加载连接到给定国家 ID 的所有国家/地区。
有没有办法解决这个问题?
【问题讨论】:
标签: sql jpa-2.0 named-query