I have an entity named Item
with relationship to another entity Category
which can be null. The two entities are as follows:
Item
@Entity
public class Item {
@Id
private String id;
private String name;
private String code;
@ManyToOne
private Category category;
}
Category
@Entity
public class Category {
@Id
private String id;
private String name;
}
Now, I have to select items having name, code or category name similar to a search term, for which I tried the following query:
"SELECT item FROM Item item "
+ "WHERE item.code LIKE :searchTerm OR item.name LIKE :searchTerm "
+ "OR item.category.name LIKE :searchTerm"
searchTerm
is set using
query.setParameter("searchTerm", "%" + searchTerm + "%");
But it doesn't result will be empty if category
is null (otherwise works). I tried the following query also.
"SELECT item FROM Item item "
+ "WHERE item.code LIKE :searchTerm OR item.name LIKE :searchTerm "
+ "OR (item.category IS NOT NULL AND item.category.name LIKE :searchTerm)"
This also didn't work. How can I make it to check for category name only if category is not null?