zoukankan      html  css  js  c++  java
  • 【MyBatis学习06】_parameter:解决There is no getter for property named in class java.lang.String

    我们知道在mybatis的映射中传参数,只能传入一个。通过#{参数名} 即可获取传入的值。

    Mapper接口文件:

    public int delete(int id) throws Exception;

    MapperL配置文件:

    <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>

    接口中我们定义了delete(int id),形参的名称为id。顺理成章的在sql段里就用#{id}去获取。
    其实这里的”参数名”可以是任意的。
    因为JAVA反射只能获取方法参数的类型,但无从得知方法参数的名字的
    上面这个例子把#{id}换成#{di},一样运行。当然为了便于阅读代码,还是用#{id}
    _parameter则是java对通过反射获取参数后,给参数取的别名。所以用#{_parameter}也行。

    但有几种情况你必须得用_parameter

    第一种情况:拼接字符${}。咱这里先不去考虑SQL注入这些问题。

    public List<User> findByName(String searchkey) throws Exception;
    <select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">
        select * from user where username like '%${searchkey}%'
    </select>

    因为要使用模糊查询。要在入参前后加上%,所以不能用占位符#{},而要用拼接字符串

    {searchkey}
    一切都似乎没有问题,运行,报错:
    Exception in thread “main”
    org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause:
    org.apache.ibatis.reflection.ReflectionException: There is no getter for property named ‘searchkey’ in ‘class java.lang.String’ ### Cause:
    org.apache.ibatis.reflection.ReflectionException: There is no getter for property named ‘searchkey’ in ‘class java.lang.String’

    问题就出在拼接字符串${searchkey}。和占位符#{}不同的是,java不会自动将${searchkey}对应成_parameter。因此只能自己写

    <select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">
        select * from user where username like '%${_parameter}%'
    </select>

    OK,一切又正常了。
    可是你没有觉得这种写法太不赏必悦目了?

    mybatis考虑到这点,你只需在接口的方法参数前加上param注解就好了。
    public List<User> findByName(@Param(value="searchkey") String searchkey) throws Exception;

    第二种情况:动态SQL中的条件判断语句中

    public List<User> findByName(String searchkey) throws Exception;
     <select id="findByName" parameterType="String" resultType="twm.mybatisdemo.pojo.User">
        <bind name="likestr" value="'%'+ searchkey +'%'"></bind>
        select * from user
        <where>
            <if test="searchkey !='' and searchkey !=null">
                username like #{likestr}
            </if>
        </where>
    </select> 

    在if和bind元素中涉及到参数searchkey。直接使用searchkey也会报上面一样的错误
    解决办法就是用_parameter替换searchkey

    或者在接口的方法参数前加上param注解。

    public List<User> findByName(@Param(value="searchkey") String searchkey) throws Exception;
  • 相关阅读:
    TXSQL:云计算时代数据库核弹头——云+未来峰会开发者专场回顾
    游戏场景下的DDoS风险分析及防护
    一站式机器学习平台TI-ONE是什么?——云+未来峰会开发者专场回顾
    带有Apache Spark的Lambda架构
    攻克数据库核心技术壁垒,实现百万级QPS的高吞吐
    想学大数据?大数据处理的开源框架推荐
    可怕!数据库竟然打破安迪-比尔定律
    什么?云数据库也能C位出道?
    协同过滤的R语言实现及改进
    Android代码规范----按钮单击事件的四种写法
  • 原文地址:https://www.cnblogs.com/abc8023/p/9601311.html
Copyright © 2011-2022 走看看