当前位置: 代码迷 >> 综合 >> MyBatis+PGSQL-JSON作where条件查询
  详细解决方案

MyBatis+PGSQL-JSON作where条件查询

热度:35   发布时间:2024-01-19 22:44:48.0

MyBatis+PGSQL-JSON作where条件查询

方式一-#>>

img

SELECT relatedparts FROM project_tasks 
WHERE (del_flag = 0 AND project_id = 'c5332adefa44715678997335b3e0519c' AND batchnum = 'b0f77a047ffdfe69af941d1bd9bb4734' 
AND relatedparts::json#>>'{0, name}' = 'B04-浙江东方职业技术学院-AS-实训楼.rvt'
AND type = 1) limit 3

结果:

image-20210528095602651

注意:使用符号#>>会和mybatis的预处理符号#冲突,导致sql语句多渲染一个空格,如下:

    <select id="queryTaskTreeForProgressSimulationList"resultType="org.jeecg.modules.production.taskplan.entity.ProjectTask">SELECT * FROM project_tasksWHERE del_flag=0AND project_id=#{projectId}AND batchnum=#{version}AND type=#{type}<if test="relatedparts">AND relatedparts::json#>>'{0, name}'=#{relatedparts}</if>LIMIT 3</select>

渲染后

Preparing: SELECT COUNT(1) FROM project_tasks WHERE del_flag = 0 AND project_id = ? AND batchnum = ? AND type = ? AND relatedparts::json# >> '{0, name}' = 'B04-浙江东方职业技术学院-AS-实训楼.rvt'
--注意#后面多了个空格导致报错

此问题最初以为是MyBatis-Plus的LambdaQueryWrapper问题,后换成普通QueryWrapper也同样存在此问题,最后换用普通MyBatis+XML编写sql查询,问题同样如此,因此确定是占位符问题。值得一提的是,使用${}替换符问题依旧如此。因此需要在MyBatis中查询PGSQL的JSON条件,改成方式二!

方式二-(column::json->>‘aaa’)::text

在mybatis和PostgreSQL Json字段作为查询条件的解决方案

img

SELECT relatedparts FROM project_tasks 
WHERE (del_flag = 0 AND project_id = 'c5332adefa44715678997335b3e0519c' AND batchnum = 'b0f77a047ffdfe69af941d1bd9bb4734' 
AND relatedparts::json->0->>'name' = 'B04-浙江东方职业技术学院-AS-实训楼.rvt'
AND type = 1) limit 3

最后以MyBatis-Plus的LambdaQueryWrapper做查询示例:

new LambdaQueryWrapper<ProjectTask>()..apply("relatedparts::json->0->>'name' = {0}", "B04-浙江东方职业技术学院-AS-实训楼.rvt");

查询成功!

  相关解决方案