Vivek Dhiman
Vivek Dhiman

Reputation: 429

Hibernate IN/ANY with custom converter in Criteria

I have a simple model say

    class A {
        @Type(type = "com.vivek.persistence.ListAsSQLArrayUserType")
        @Column(name = "string_array", columnDefinition = "text[]")
        List<String> stringArray;
    }

Now I want to search any item exists in the stringArray Column. I can do this simply using sql native query :

select * from A WHERE 'abc' = any(string_array)

But I am not able to figure out any way through Hibernate Criteria API. I have tried IN predicate but it simply do not work and return empty result. Any help would be appreciated.

Upvotes: 2

Views: 731

Answers (2)

Alex A
Alex A

Reputation: 63

I had applied the solution below to column of ENUM type with help of @Vivek Dhiman answer. While building criteria:

Before:

builder.equal(from.get("columnName"), criteria.getValue());

After:

builder.equal(from.get("columnName"), HttpMethod.valueOf(criteria.getValue()));

Column

@Enumerated(EnumType.STRING)
@Column(name = "column_name")
private HttpMethod columnName;

Builder:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

Upvotes: 0

Vivek Dhiman
Vivek Dhiman

Reputation: 429

I have found the solution which can be specific to postgres using criteriaBuilder.function(). It resolved my issue.

String value = "abc"; // anything
criteriaBuilder.equal(criteriaBuilder.literal(value), criteriaBuilder.function("any", String.class, root.get(name)));

Upvotes: 2

Related Questions