好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mybatis对传入基本类型参数的判断方式

对传入基本类型参数的判断

mybatis的xml文件的sql语句中parameterType为基本类型,如:

?

1

2

3

4

5

< select id = "getCustomer" parameterType = "Integer" resultType = "Customer" >

    select * from customer

    where

    < if test = "id != null" >id=#{id}</ if >

< select >

会报错:There is no getter for property named 'id' in 'class java.lang.Integer'

这是因为Integer对象中没有id属性

解决办法

?

1

2

3

4

5

< select id = "getCustomer" parameterType = "Integer" resultType = "Customer" >

    select * from Customer

    where

    < if test = "_parameter != null" >id=#{_parameter}</ if >

< select >

即将接收参数的参数名改为_parameter,注意改成其他参数名没用。

传入基本类型参数时test判断报错

在使用mybatis的时候出现了这样的问题:

?

1

2

//Dao层的接口中的代码

List<Map<String,Object>> getName(String username);

?

1

2

3

4

5

6

7

8

9

10

//对应的mapper中的代码

< select id = "getName" resultType = "java.util.Map" >

     select name,client_id

     from table1

     < where > 

         < if test = " username!= null and username!='' " >

             and username= #{id}

         </ if >

     </ where > 

</ select >

//报的错误
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: 
There is no getter for property named 'username' in 'class java.lang.String'

分析

There is no getter for property named ‘username’ in ‘class java.lang.String’,这句话打大概意思是:在[class java.lang.String]中没有名为[username]的属性的getter方法。因为mybatis默认采用ONGL解析参数,所以会自动采用对象树的形式取string.num值,引起错误。

解决办法

if test中的id用_parameter替换,而实际的语句不需要修改and a.id =#{id},因为Mybatis当只传入一个参数时#{ } 中的内容没有要求。

在Mapper中给出入参设置名称,例:public … getName(@Param([username]) String username);这样修改后我们前面的写法就不会报错了。

小结一下

在传入基本类型的数据时,if标签中test判断的书写hi根据ognl表达式来取值的,所以不能直接写参数的名称,要利用_parameter来替代,或者利用注解@Pram("")来给参数起别名。

补充一点点: 标签when中的test属性也有同样的问题!!!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/cfp008/article/details/52719122

查看更多关于mybatis对传入基本类型参数的判断方式的详细内容...

  阅读:21次