Search code examples
javahibernatesql-likehibernate-annotations

Hibernate - SQL annotation @Where clause with multiple LIKE operator on the same column name


I want to add one or more LIKE operator in the below @Where clause for the same column name. But, if i add LIKE with OR/AND operator am not getting the exact result. How i can simplify this scenario to get the Exact value.

Please find my code below.

@OneToMany( mappedBy = "product", cascade = CascadeType.ALL)
@Where(clause="name NOT LIKE '%long%' AND name LIKE '%description'")
private List<ProductAttr> productAttr;
public List<ProductAttr> getProductAttr() {
    return productAttr;
}

public void setProductAttr(List<ProductAttr> productAttr) {
    this.productAttr = productAttr;
}

If i use AND Operator

@Where(clause="name NOT LIKE '%long%' AND name LIKE '%description' AND name 
LIKE '%source%'")

It will gives null pointer exception for some records.

If i use OR Operator

    @Where(clause="name NOT LIKE '%long%' AND name LIKE '%description' OR 
    name LIKE '%source%'")

Am missing some values here.

What will be the best approach to solve this scenario.?


Solution

  • @Where(clause="name NOT LIKE '%long%' AND name LIKE '%description' AND name LIKE '%source%'")
    

    Above query means each record of name column must not contain long word and must contain description word and must contain source word

    @Where(clause="name NOT LIKE '%long%' AND name LIKE '%description' OR name LIKE '%source%'")
    

    Above query means each record of name column must not contain long word but must contain either description or source word

    Hence the resultSet will differ for both the queries.