简体   繁体   中英

Return data even if the foreign key is null in HQL

I have a Product Table that joins a ProductCategory table with @ManyToOne and @OneToMany relations. Product :

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "category_id")
@NotFound(action=NotFoundAction.IGNORE)
private ProductCategory productCategory;

Category :

@OneToMany(fetch = FetchType.LAZY, mappedBy="productCategory" ,cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JsonBackReference
@OrderBy("id desc")
private Set<Product> products = new HashSet<Product>(); 

I have this repository method that retrieves data from Product table:

@Query("SELECT p from Product p where cast(p.id as string) like :x or p.name like :x or p.description like :x or p.sku like :x or p.productCategory.name like :x")
public Page<Product> search(@Param("x") String keyword, Pageable pageable);

This method does not return the products where their categories is null. How to retrieve the products even if I have null on the productCategory column.

我通过LEFT JOIN查询添加(实际上) LEFT JOIN来解决了这个问题:

"SELECT p from Product p left join p.productCategory where cast(p.id as string) like :x or p.name like :x or p.description like :x or p.sku like :x or p.productCategory.name like :x"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM