In my PostgreSQL table I have a parts
column of type json
. I want to check if the given argument is contained in my json column.
This query works in the database:
select * from elements we
where parts::text like '%"CHEST"%'
However, it doesn’t work in my repository, I’m not sure but it’s probably jpql:
@Override
public List<ElementView> test() {
return entityManager.createQuery(
"SELECT DISTINCT w FROM ElementView w " +
"WHERE we.parts::text like '%CHEST%'", ElementView.class)
.getResultList();
}
Is it possible to use this query (or another) to check the json array in the repository?
2
Answers
See if this example solves it :
Notice there is two operators -> for selection and
->> for predicates.
They doesnt work when get their roles confused.
The query "in your repository" can’t work because the table alias is
w
, but you referencewe
:Also not sure about your upper-case letters in the search term
'%CHEST%'
. You might want:See:
But this is hugely expensive and unspecific. Depending on what "contained" is supposed to mean exactly, and if your JSON column is actually type
jsonb
(much) more efficient queries with index support are possible. Like …Does "CHEST" exist as top-level key or array element (not as value) within the jsonb column?
See: