• (八)MyBatis中参数的处理


    Mybatis学习目录

    上一篇:(七)Mybatis传值中#{}和${}的区别,及别名机制
    下一篇:(九)MyBatis查询语句的返回值类型

    环境

    数据库:t_student
    Mybatis工具类
    依赖
    mybatis-config.xml、logback.xml
    pojo类:Student
    除了t_student、Student,其他可以去复制之前的
    t_student

    • id 主键(自增)[BIGINT] 学生id
    • name [VARCHAR] 学生姓名
    • age [INT] 学生年龄
    • height [DOUBLE] 学生身高
    • birth [DATE] 学生出生日期
    • sex [CHAR] 学生性别

    数据
    请添加图片描述

    Student类:

    public class Student {
        private Long id;
        private String name;
        private Integer age;
        private Double height;
        private Date birth;
        private Character sex;
    
        public Student() {
        }
    
        public Student(Long id, String name, Integer age, Double height, Date birth, Character sex) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.height = height;
            this.birth = birth;
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name=" + name +
                    ", age=" + age +
                    ", height=" + height +
                    ", birth=" + birth +
                    ", sex=" + sex +
                    '}';
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Double getHeight() {
            return height;
        }
    
        public void setHeight(Double height) {
            this.height = height;
        }
    
        public Date getBirth() {
            return birth;
        }
    
        public void setBirth(Date birth) {
            this.birth = birth;
        }
    
        public Character getSex() {
            return sex;
        }
    
        public void setSex(Character sex) {
            this.sex = sex;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    单个简单类型参数

    接口中的方法参数是单个简单参数,并且数据类型是简单类型,mybatis可以自动做类型推断
    简单类型包括:

    • byte short int long float double char
    • Byte Short Integer Long Float Double Character
    • String
    • java.util.Date
    • java.sql.Date

    业务需求:根据name查、根据id查、根据birth查、根据sex查
    创建一个StudentMapper接口,在接口中添加相应的方法

    public interface StudentMapper {
        List<Student> selectById(Long id);
        List<Student> selectByName(String name);
        List<Student> selectByBirth(Date date);
        List<Student> selectBySex(Character sex);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    创建映射文件StudentMapper.xml,配置sql语句

    	<select id="selectById" resultType="student">
            select *
            from t_student
            where id = #{id}
        </select>
    
        <select id="selectByName" resultType="student">
            select *
            from t_student
            where name = #{name}
        </select>
    
        <select id="selectByBirth" resultType="student">
            select *
            from t_student
            where birth = #{birth}
        </select>
    
        <select id="selectBySex" resultType="student">
            select *
            from t_student
            where sex = #{sex}
        </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    测试程序
    通过id查询:

    	@Test
        public void testSelectById(){
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectById(1L);
            students.forEach(student -> System.out.println(student));
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请添加图片描述
    通过name查询:

    	@Test
        public void testSelectByName(){
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectByName("张三");
            students.forEach(student -> System.out.println(student));
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请添加图片描述
    通过birth查询:

    	@Test
        public void testSelectByBirth() throws ParseException {
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectByBirth(new SimpleDateFormat("yyyy-MM-dd").parse("2022-09-01"));
            students.forEach(student -> System.out.println(student));
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请添加图片描述
    根据sex查询:

    	@Test
        public void testSelectBySex(){
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectBySex('女');
            students.forEach(student -> System.out.println(student));
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请添加图片描述
    通过测试得知,对于简单类型Mybatis是可以做自动类型识别的,可以自动推断出调用哪个ps.setXXX()方法。
    实际上,在SQL映射文件里面中配置比较完整的学法是在select标签里面,加一个parameterType属性,指定其参数类型,这个属性需要填类型的全限定名称,但在Mybatis内置了很多别名,我们用这些别名即可,当然,对于简单类型来说,Myabtis是由自动类型推断机制的,我们可以不用设置这个属性。

    Mybatis内置的别名对应列表

    别名映射的类型
    _bytebyte
    _longlong
    _shortshort
    _intint
    _integerint
    _doubledouble
    _floatfloat
    _booleanboolean
    stringString
    byteByte
    longLong
    shortShort
    intInteger
    integerInteger
    doubleDouble
    floatFloat
    booleanBoolean
    dateDate
    decimalBigDecimal
    bigdecimalBigDecimal
    objectObject
    mapMap
    hashmapHashMap
    listList
    arraylistArrayList
    collectionCollection
    iteratorIterator

    Map参数

    业务需求:根据name和age查询
    StudentMapper接口添加方法

    int insertStudentByMap(Map<String ,Object> map);
    
    • 1

    StudentMapper.xml文件配置

    	<insert id="insertStudentByMap">
            insert into t_student value(null ,#{姓名},#{年龄},#{体重},#{生日},#{性别})
        </insert>
    
    • 1
    • 2
    • 3

    测试程序

    	@Test
        public void testInsertStudentByMap() throws ParseException {
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            Map<String,Object> map = new HashMap<>();
            map.put("姓名","赵六");
            map.put("年龄","20");
            map.put("体重",1.81);
            map.put("性别","男");
            map.put("生日",new SimpleDateFormat("yyyy-MM-dd").parse("2022-09-01"));
            int students = mapper.insertStudentByMap(map);
            session.commit();
            System.out.println(students);
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    请添加图片描述

    这种方式是手动封装Map集合,将每个条件以key和value的形式存放到集合中。然后在使用的时候通过#{map集合的key}来取值。发现Map集合参数Mybatis也可以做自动类型推断的。

    实体类参数

    业务需求:插入⼀条Student数据
    StudentMapper接口添加方法

    int insertStudentByPojo(Student student);
    
    • 1

    StudentMapper.xml文件配置

    	<insert id="insertStudentByPojo">
            insert into t_student value(null ,#{name},#{age},#{height},#{birth},#{sex})
        </insert>
    
    • 1
    • 2
    • 3

    测试程序

    	@Test
        public void testInsertStudentByPojo() throws ParseException{
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            int students = mapper.insertStudentByPojo(new Student(null,"赵六",20,1.81,new SimpleDateFormat("yyyy-MM-dd").parse("2022-09-01"),'男'));
            session.commit();
            System.out.println(students);
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    运⾏正常,数据库中成功添加⼀条数据。
    请添加图片描述
    发现实体类,Mybatis也可以做自动类型推断。

    多参数

    多参数,mybatis框架底层会自动创建一个map集合

    • mybatis高版本map的存储方式:

           map.put("arg0",name);
           map.put("arg1",sex);
           或者
           map.put("param1",name);
           map.put("param2",sex);
      
      • 1
      • 2
      • 3
      • 4
      • 5
    • mybatis低版本map的存储方式:

          	 map.put("0",name);
            map.put("1",sex);
      
      • 1
      • 2

    业务需求:通过name和sex查询
    StudentMapper接口添加方法

    List<Student> selectByNameAndSex(String name,Character sex);
    
    • 1

    所以当有多个参数时SQLMapper映射文件的sql语句传值时#{}里面只能填argX或者paramX,有几个参数填几个
    例如这个方法是

    • name = #{arg0} and sex = #{arg1}
    • 或name = #{param1} and sex = #{param2}
    • 或者混合使用,但必须与参数对应:
      name = #{param1} and sex = #{arg1}
      或name = #{arg0} and sex = #{param2}

    StudentMapper.xml文件配置:

    	<select id="selectByNameAndSex" resultType="student">
            select *
            from t_student
            where name = #{arg0} and sex = #{param2}
        </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试程序

    	 @Test
        public void testSelectByNameAndSex(){
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectByNameAndSex("张三",'男');
            students.forEach(student -> System.out.println(student));
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请添加图片描述

    @Param注解(命名参数)

    在SQLMapper.xml映射文件里面使用argX或paramX方式进行传值的话,发现可读性非常差,对于这种情况,可以使用@Param注解来配置传值方式,提供可读性,这个注解是Mybatis内置的
    相当于把argX替换了存储方式,之前的存储方式paramX还是可以用的,因为在Mybatis底层认为param是一个通用的key请添加图片描述

    	map.put("arg0",name);
    	map.put("arg1",sex);
    	替换了,argX
    	map.put("name",name);
    	map.put("sex",sex);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    StudentMapper接口添加方法:

    List<Student> selectByNameAndSex2(@Param("name") String name, @Param("sex") Character sex);
    
    • 1

    StudentMapper.xml文件配置:

        <select id="selectByNameAndSex2" resultType="student">
            select *
            from t_student
            where name = #{name} and sex = #{sex}
        </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试程序

        @Test
        public void testSelectByNameAndSex2(){
            SqlSession session = SqlSessionUtil.getSession();
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            List<Student> students = mapper.selectByNameAndSex2("张三",'男');
            students.forEach(student -> System.out.println(student));
            SqlSessionUtil.close(session);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    请添加图片描述

  • 相关阅读:
    20221115 今天的世界发生了什么
    二叉树的建立和遍历
    JS获取音频的总时长,解决audio.duration 为 NaN || Infinity 问题
    架构设计基础
    Python实现fan茄小说内容下载
    Google Earth Engine ——快速实现MODIS影像NDVI动画的在线加载并导出
    vue实现组件功能复用 mixins
    九章云极DataCanvas大模型系列成果发布会重磅来袭,诚邀见证!
    VIM插件安装与配置
    后续遍历非递归算法
  • 原文地址:https://blog.csdn.net/weixin_45832694/article/details/127670807