mybatis 动态更换表名,用以动态访问不同表的数据(#{} 、${})

原文地址:https://blog.csdn.net/qq_25221835/article/details/86711987

贴个图片,方便查看重点:

 或者:

看了上面,大家就应该要猜到我等下要说什么了,我再贴下我之前的问题代码:

错误代码一:

1.所有参数都用  #{}

错误原因:错误的关键就在于  #{table}  ,其实本质还是  #{}   和  ${} 的区别

简单理解就是  #{} 会给 你的实参加个 单引号 ,所以 表名就变成了   'tb_plan_result_detail',然后你执行sql:

SELECT a.error_detail as "errorDetail",a.only_id AS "onlyId" from  'tb_plan_result_detail' a  肯定就会出错了

所以表名 必须使用   ${table}。但是你若是 在条件参数中使用 $,就要加 单引号,因为 ${} 不会默认加个单引号,如上面的

a.tablename ='${tableName}'

<select id="findPlanResultDetailInfo" resultType="PlanResultDeatil">
     select * from(
        SELECT a.error_detail as "errorDetail",
        a.only_id AS "onlyId"
        from #{table} a
        <where>
            <if test="resultId != null and resultId != ''">
                a.result_id = #{resultId}
            </if>
            <if test="tableName != null and tableName != ''">
                AND a.tablename = #{tableName}
            </if>
            <if test="fieldName != null and fieldName != ''">
                AND a.fieldname = #{fieldName}
            </if>
            <if test="ruleType != null and ruleType != ''">
                AND a.rule_type = #{ruleType}
            </if>
            <if test="errorType != null and errorType != ''">
                AND a.error_type = #{errorType}
            </if>
        </where>
        ORDER BY a.tablename,a.fieldname
       )where rownum &lt;= 3 
</select>
 

错误代码二:

这个错误是关于 接口的,直接看代码:

public List<PlanResultDeatil> findPlanResultDetailInfo(@Param("planResultDetail") PlanResultDeatil planResultDetail);

我加这个注解,planResultDetail , 但我 xml中,直接使用的是 planResultDetail类中它的属性,比如#{tableName},其实不使用

@Param("planResultDetail") 反而不会出错,使用了@Param("planResultDetail") ,就一定得在 xml中表明你使用的参数,不然xml无法识别它,因为你声明的是@Param("planResultDetail") ,你凭什么直接使用 #{tableName}。

正解就是  #{planResultDetail.tableName}

 

总结:

其实,这些都是非常基础的问题,但由于以习惯去认识问题,浪费了很多时间。要多总结,才能多多进步啊~
————————————————
版权声明:本文为CSDN博主「一彡十」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_25221835/article/details/86711987

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值