SQL Server JPA Specifications Like Expression with "N" before search text

mdfafbf1  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(94)

I'm developing a Spring Boot application using Spring Data JPA with SQL Server 2017. I want to use LIKE expression to query Khmer Unicode data. SELECT statement I mention below is working fine when I executed it in SQL Server Management Studio

SELECT * FROM merchant_holiday_setting WHERE description_kh LIKE N'%ទិវា%'

But I want to know how to apply it with JPA Specification Criteria here's my code in Spring Boot

override fun findAllList(q: String?, page: Int, size: Int): Page<MerchantHolidaySetting>? {
    return mchHolidayRepo.findAll({ root, cq, cb ->
        val predicate = ArrayList<Predicate>()
        q?.let {
            println("Query $q")
            val descEn = cb.like(cb.upper(root.get("description")), "%${q.toUpperCase()}%")
            val descKh = cb.like(root.get("descriptionKh"), "%$q%")
            predicate.add(cb.or(descEn, descKh))
        }
        predicate.add(cb.isTrue(root.get("status")))
        cq.orderBy(cb.asc(root.get<Date>("holidayDate")))
        cb.and(*predicate.toTypedArray())
    }, PageRequest.of(page, size))
}

Please help me to find out the answer. Thanks in advance!!

ngynwnxp

ngynwnxp1#

By default, JPA does not use the N'' or unicode specifier. To achieve this, you'll need a SQL interceptor to turn the first ' into N' using regex.

public class CustomSQLInterceptor extends EmptyInterceptor {

    @Override
    public String onPrepareStatement(String sql) {
        sql = sql.replaceAll("('[^']+')", "N$1");
        return sql;
    } }

and in your application.properties file, add this line to register your interceptor:

spring.jpa.properties.hibernate.ejb.interceptor=package.path.CustomSQLInterceptor

相关问题