Search code examples
hibernatespring-bootjakarta-eehql

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.


Solution

  • I solved the problem with adding (indeed) a LEFT JOIN to the query :

    "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"