I have a below requirement in my project:
(1) Request object to an API which is off list type (of strings).
(2) We are using Hibernate Criteria to fetch the resultSet from the mysql database.
(3) One of the columns is having Pipe delimited values.
(4) We have to fetch the rows against each of the request object's values.
Table: user_info
-----------------------------------------------------------
user_id user_name .. .. .. .. hobbies
-----------------------------------------------------------
101 johnSmith .. .. .. .. Traveling|Painting|Gardening
102 tomWatch .. .. .. .. Gardening|Reading|Fishing
103 robertPatt .. .. .. .. Dancing|Gardening|Swimming|Blogging
104 julieAdams .. .. .. .. Bicycling|Fishing|Socializing
JSON Request object:
{
searchParams : {
hobbies : [
"Gardening",
"Fishing",
"Reading"
],
..
..
..
}
}
Java Code
if(!CollectionUtils.isEmpty(searchParams.getHobbies())) {
List<String> reqHobbies = searchParameters.getHobbies();
Disjunction disjunction = Restrictions.disjunction();
for(String hobby : reqHobbies) {
Criterion criterion = Restrictions.like("hobbies", "|" + hobby + "|");
disjunction.add(criterion);
}
criteria.add(disjunction);
}
This query will not work as the starting of the value (from table) is not having "|" symbol..
If I modify the critieria API to generate the query in the following fashion,
select * from user_info
where hobbies like '%Gardening|%' or hobbies like '%Fishing|%' or hobbies like '%Reading|%'
or hobbies like '%|Gardening|%' or hobbies like '%|Fishing|%' or hobbies like '%|Reading|%'
or hobbies like '%|Gardening%' or hobbies like '%|Fishing%' or hobbies like '%|Reading%';
This design also has a flaw. The only way to solve this by using FIND_IN_SET.
Mysql query:
select * from user_info
where hobbies find_in_set('Gardening', replace(hobbies, '|', ','))
or hobbies find_in_set('Fishing', replace(hobbies, '|', ','))
or hobbies find_in_set('Reading', replace(hobbies, '|', ','));
How to create a find_in_set query using Hibernate Criteria? Using @Formula ?