软件编程
位置:首页>> 软件编程>> java编程>> mybatis group by substr函数传参报错的解决

mybatis group by substr函数传参报错的解决

作者:罗罗诺亚F  发布时间:2022-09-10 03:44:34 

标签:mybatis,group,substr

mybatis group by substr传参报错

报异常

### Cause: java.sql.SQLSyntaxErrorException: ORA-00979: 不是 GROUP BY 表达式

SELECT
    SUBSTR( region_code, 1,#{ queryMap.groupCodeLength, jdbcType = INTEGER } ) AS "region_code",
    count( CASE WHEN TYPE = 1 THEN 0 END ) AS "like",
    count( CASE WHEN TYPE = 2 THEN 0 END ) AS "roast" 
FROM
    t_pub_sentiment 
WHERE
    1 = 1 
GROUP BY
    SUBSTR(region_code,1,#{ queryMap.groupCodeLength,jdbcType = INTEGER })

更改后:

SELECT
    SUBSTR( region_code, 1, $ { queryMap.groupCodeLength } ) AS "region_code",
    count( CASE WHEN TYPE = 1 THEN 0 END ) AS "like",
    count( CASE WHEN TYPE = 2 THEN 0 END ) AS "roast" 
FROM
    t_pub_sentiment 
WHERE
    1 = 1 
GROUP BY
    SUBSTR( region_code, 1, $ { queryMap.groupCodeLength } )

原因

#{} 和 ${} 在预编译中的处理是不一样的。#{} 在预处理时,会把参数部分用一个占位符 ? 代替。而 ${} 则只是简单的字符串替换。

${}有sql注入的风险,需谨慎使用。

使用group by 分组查询返回为null

我在使用mybatis进行分组查询时数据库有数据,但是mybatis返回为null,使用mybatis版本为3.4.1

解决方法

在resultMap的result标签中添加 property属性

如下:

<resultMap id="deptMap" type="java.util.Map">
        <result column="id" property="id"/>
        <result column="dept_name" property="deptname"/>
        <result column="count(1)" property="count"/>
    </resultMap>
  
 <select id="getDeptByIdStep" resultMap="deptMap">
  select  id,dept_name,count(1)  from tbl_dept where dept_id=#{id} group by id;
 </select>

我在第一次使用时没有添加property导致mybatis返回null,添加后就可以正常返回。

dao层代码

public List<Map> getDeptByIdStep(Integer id);

来源:https://blog.csdn.net/Tracycater/article/details/84674359

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com