概要
JPAを使用してのJSON型カラムのValue値検索について調べたので、共有として。
Specificationにて検索するケース。
結論
MySQLの関数を使用する。
JSON_EXTRACT
SELECT * FROM ATABLE WHERE JSON_EXTRACT("column_name", "$.key") = value;
なので、Spring JPAのSpecificationを使用する場合、
public Specification<T> jsonSearch(String key, String val) {
return (root, query, cb) -> {
return cb.like(cb.function("JSON_EXTRACT", String.class, root.get("names"), cb.literal("$." + key)),
"%" + val + "%");
};
}