【mybatis】传参问题:多个参数中同一类型和不同类型

版权声明:整理不易,转载请注明出处。 https://blog.csdn.net/linmengmeng_1314/article/details/86088377

在项目中如果一个方法中的参数都是同一个类型,那么我们在mapper文件中写查询语句时,直接就可以用parameterType="java.lang.String"就可以了,但是类型不一样的时候,比如我们需要穿两个参数到SQL语句中,一个是String类型的,一个是int类型的,再这样写就不行了。

因为在查询的时候,当传进去的参数为string类型时,mybatis会自动将参数用''给括起来。

并且还有一个问题,当两个参数类型相同时,mapper文件内可以这么写:

<select id="selectUser" resultType="com.lin.demo.entity.User" parameterType="String">
	select * from t_user where username = #{username} and depart_name = #{departName}
</select>

mapper.java

User selectUser(String username, String departName);

直接这样写,好像也没什么问题,毕竟SQL语句中,直接使用了参数名接收参数,但是我发现有的时候会报这个错误:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'username' not found. Available parameters are [1, 0, param1, param2]
	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:76)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:399)
	at com.sun.proxy.$Proxy32.selectList(Unknown Source)
...

这种情况就是参数注入失败的问题,需要在mapper.java 的方法里面加上@Param进行参数绑定,这样就可以了。

User selectUser(@Param("username")String username, @Param("departName")String departName);

但参数类型不同的时候,可以尝试使用map传参:

List<ShopOrder> selectLastData(Map<String, Object> map);
	<select id="selectLastData" resultType="com.thinkgem.jeesite.modules.ejt.entity.ShopOrder1" parameterType="map">
		select * from 718shop_order where order_state= 10 and buyer_id = #{memberId} ORDER BY add_time DESC LIMIT #{orderNum}
	</select>

最后在controller里面用到这个selectLastData方法时,直接将参数放到里面就可以了。

还有一个问题就是在使用mysql的条件查询时,将limit后面的数字当成字符串类型传进去时报错了,这里记录一下,limit后面的数字,必须是int类型的,因为String类型的参数,在进行SQL拼接时,数字外面自动加了一个单引号,此时就会出现SQL语句的异常

SQL: select * from 718shop_order where order_state= 10 and buyer_id = ? ORDER BY add_time DESC LIMIT ?
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''9'' at line 1
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''9'' at line 1
	at org.springframework....

猜你喜欢

转载自blog.csdn.net/linmengmeng_1314/article/details/86088377