net.sf.jsqlparser.statement.select.SubSelect cannot be cast to net.sf.jsqlparser.schema.Table

记录一下,mybatis-plus 使用时 在 select 需要查询的字段中使用变量和函数,出现的异常。如果你也是这种场景出现的问题,可以参考我的解决方案

net.sf.jsqlparser.statement.select.SubSelect cannot be cast to net.sf.jsqlparser.schema.Table

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.ClassCastException: net.sf.jsqlparser.statement.select.SubSelect cannot be cast to net.sf.jsqlparser.schema.Table
### The error may exist in file [D:\java\target\classes\mapping\DeviceMapper.xml]
### The error may involve com.parcel.mapper.DeviceMapper.findPage_mpCount
### The error occurred while executing a query
### Cause: java.lang.ClassCastException: net.sf.jsqlparser.statement.select.SubSelect cannot be cast to net.sf.jsqlparser.schema.Table

 第一种场景

 代码示例

<select id="findPage" resultType="com.vo.DeviceFindPageVO">
	SELECT
		d.id,
    CASE WHEN 
        d.agent_id = #{agentId}        #### 这里使用变量出错
    THEN
		0 
    ELSE 
        1 
	END sales 
	FROM
		pt_device d
		JOIN pt_device_group dg ON d.group_id = dg.id
		JOIN pt_device_server ds ON d.server_id = ds.id
		LEFT JOIN sys_user u1 ON d.agent_id = u1.id AND u1.type = 2
		<if test="agentId !=null and agentId != ''">
			and u1.parent_id = #{agentId}
		</if>
		LEFT JOIN sys_user u2 ON d.user_id = u2.id AND u2.type = 4
		${ew.customSqlSegment}
</select>

解决方法

// xml
<select id="findPage" resultType="com.vo.DeviceFindPageVO">
	SELECT
		d.id
        ${ew.sqlSelect}            #### 使用 mybatisplus的常量拼接符
	FROM
		pt_device d
		JOIN pt_device_group dg ON d.group_id = dg.id
		JOIN pt_device_server ds ON d.server_id = ds.id
		LEFT JOIN sys_user u1 ON d.agent_id = u1.id AND u1.type = 2
		<if test="agentId !=null and agentId != ''">
			and u1.parent_id = #{agentId}
		</if>
		LEFT JOIN sys_user u2 ON d.user_id = u2.id AND u2.type = 4
		${ew.customSqlSegment}
</select>

// java
queryWrapper.select(", case when d.agent_id = " + agentId + " then 0 else 1 end sales");

第二种场景

使用count,查询数据条数的时候,SQL语句中使用函数,例如:DISTINCT、GROUP BY、LEFT等等,也会报错。

示例:

// 你的sql语句
select id from table group by type;
// mp分页的时候,mp会查询数据总数,page<pageNum,pageSize,默认查询总数>
// 会这样查询,然后这句话就会报错,说不能使用函数
select count(*) from (select id from table group by type) as total;

这个时候真的是没办法了,真的是mp的bug,mp官网的github上一大堆bug

解决方法:

使用视图 view ,然后查询这个视图的数据

CREATE OR REPLACE VIEW 视图名称 (字段) AS select id from table group by type;

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又逢乱世

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值