在一对多情况下,JPA如何加入?

时间:2018-09-05 13:20:28

标签: spring jpa spring-data-jpa jpql

我有两个实体Outlet和产品,它们之间具有一对多的关系-

@Entity
public class Outlet{

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id;

@Fetch (FetchMode.SELECT)
@OneToMany(mappedBy = "outletProduct",fetch = FetchType.LAZY)
List<Product> products;

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
Boolean isActive;

@ManyToOne
@JoinColumn(name = "outletId")
Outlet outletProduct;

现在,我希望产品处于活动状态的奥特莱斯是真实的。

我正在为以下内容编写JPQL-

 @Query("Select op From Outlet op  join op.products pro where pro.isActive=1  order by op.id")
 List<Outlet>  findAllByVarietiesPriceTimePeriodIn( );

但是我仍然在获得带有proactives isactive false的商店。 请提出建议。

我想获得将来自此sql查询的结果-

SELECT * FROM outlet join product on product.outlet_id= outlet.id where product.is_active=1 ;

1 个答案:

答案 0 :(得分:0)

  

我想让Outlet至少拥有一个产品,但我不希望它的isactive false产品。现在我将所有产品都列在列表中

它是not recommended,但可以使用JOIN FETCH

Select op From Outlet op join fetch op.products pro where pro.isActive = 1 order by op.id