MyBatis的parameterType传入参数类型

矫情吗;* 2021-12-07 12:37 391阅读 0赞

1、mybatis传入的参数可以是基本数据类型int、string、long、Date;或者是类(JavaBean、Integer等)和Map

2、如何获取参数中的值:

2.1 基本数据类型:#{参数} 获取参数中的值

2.2 复杂数据类型:#{属性名} ,map中则是#{key}

3、常用类型参数的案例

  3.1传入List

  1. <select id="findUserListByIdList" parameterType="java.util.ArrayList" resultType="User">
  2. select * from user user
  3. <where>
  4. user.ID in (
  5. <foreach collection="list" item="id" index="index" separator=",">
  6. #{id}
  7. </foreach>
  8. )
  9. </where>
  10. </select>

在使用foreach的时候最关键的也是最容易出错的就是collection属性。

该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:

  1. 1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  2. 2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  3. 3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可

 3.2传入数组

  

  1. <select id="findUserListByIdList" parameterType="java.util.HashList" resultType="User">
  2. select * from user user
  3. <where>
  4. user.ID in (
  5. <foreach collection="array" item="id" index="index" separator=",">
  6. #{id}
  7. </foreach>
  8. )
  9. </where>
  10. </select>

  3.3传入map

  1. 该案例中:
  2. map {
  3. idList”:“{...}”,
  4. id”:“”,
  5. code”:“”,
  6. }
  7. <select id="exists" parameterType="java.util.HashMap" resultType="java.lang.Integer">
  8. SELECT COUNT(*) FROM USER user
  9. <where>
  10. <if test="code != null">
  11. and user.CODE = #{code}
  12. </if>
  13. <if test="id != null">
  14. and user.ID = #{id}
  15. </if>
  16. <if test="idList !=null ">
  17. and user.ID in (
  18. <foreach collection="idList" item="id" index="index" separator=",">
  19. #{id}
  20. </foreach>
  21. )
  22. </if>
  23. </where>
  24. </select>
  25. collection中放键名

  3.4传入java对象

  1. 和传入map类似,例如java对象为
  2. public class User{
  3. private int id;
  4. private String code;
  5. private List<Integer> idList;
  6. }
  7. <select id="findUserList" parameterType="User" resultType="java.lang.Integer">
  8. SELECT COUNT(*) FROM USER user
  9. <where>
  10. <if test="code != null">
  11. and user.CODE = #{code}
  12. </if>
  13. <if test="id != null">
  14. and user.ID = #{id}
  15. </if>
  16. <if test="idList !=null ">
  17. and user.ID in (
  18. <foreach collection="idList" item="id" index="index" separator=",">
  19. #{id}
  20. </foreach>
  21. )
  22. </if>
  23. </where>
  24. </select>
  25. collection里面放变量名

转载:

作者:Remember_Ray
来源:CSDN
原文:https://blog.csdn.net/q343509740/article/details/80578832

转载于:https://www.cnblogs.com/DiiDii/p/10990127.html

发表评论

表情:
评论列表 (有 0 条评论,391人围观)

还没有评论,来说两句吧...

相关阅读