【MyBatis】参数处理

表的设计和pojo类的创建

1.提前准备数据库表,设置id为主键自增

2.student类

package com.powernode.mybatis.pojo;

import java.util.Date;

public class Student {
    private Long id;
    private String name;
    private Integer age;
    private Double height;
    private Character sex;
    private Date birth;
    // constructor
    // setter and getter
    // toString
}

1 单个简单类型参数

 简单类型包括:

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

StudentMapper接口

package com.powernode.mybatis.mapper;

import com.powernode.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;
import java.util.Map;

public interface StudentMapper {

    List<Student> selectById(Long id);
    List<Student> selectByName(String name);
    List<Student> selectByBirth(Date birth);
    List<Student> selectBySex(Character sex);
}

StudentMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.powernode.mybatis.mapper.StudentMapper">
 

    <select id="selectById" resultType="com.powernode.mybatis.pojo.Student" parameterType="long">
        select * from t_student where id = #{id};
    </select>
    <select id="selectByName" resultType="com.powernode.mybatis.pojo.Student" parameterType="string">
        select * from t_student where name = #{name};
    </select>
    <select id="selectByBirth" resultType="com.powernode.mybatis.pojo.Student" parameterType="date">
        select * from t_student where birth = #{birth};
    </select>
    <select id="selectBySex" resultType="com.powernode.mybatis.pojo.Student">
        select * from t_student where sex = #{sex}
    </select>
   
</mapper>

Test

package com.powernode.mybatis.test;

import com.powernode.mybatis.mapper.StudentMapper;
import com.powernode.mybatis.pojo.Student;
import com.powernode.mybatis.utilts.SqlSessionUntil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StudentMapperTest {

    @Test
    public void testSelectBySex() {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Character sex = '男';
        List<Student> students = mapper.selectBySex(sex);
        students.forEach(student -> {
            System.out.println(student);
        });
        sqlSession.close();
    }

    @Test
    public void testSelectByBirth() throws Exception {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birth = sdf.parse("1980-10-11");
        List<Student> students = mapper.selectByBirth(birth);
        students.forEach(student -> {
            System.out.println(student);
        });
        sqlSession.close();
    }

    @Test
    public void testSelectByName() {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectByName("李四");
        students.forEach(student -> {
            System.out.println(student);
        });
        sqlSession.close();
    }

    @Test
    public void testSelectById() {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectById(1L);
        students.forEach(student -> {
            System.out.println(student);
        });
        sqlSession.close();
    }
}

运行结果截图及结论

测试通过,不一个个测试了

其实SQL映射文件中的配置比较完整的写法是:

​
<select id="selectByName" resultType="com.powernode.mybatis.pojo.Student"                parameterType="string">
    select * from t_student where name = #{name , javaType=String, jdbcType=VARCHAR};
</select>

​

其中sql语句中的javaType,jdbcType,以及select标签中的parameterType属性,都是用来帮助mybatis进行类型确定的。不过这些配置多数是可以省略的。因为mybatis它有强大的自动类型推断机制。

  • javaType:可以省略
  • jdbcType:可以省略
  • parameterType:可以省略

如果参数只有一个的话,#{} 里面的内容就随便写了。对于 ${} 来说,注意加单引号

2 Map参数

StudentMapper接口

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

StudentMapper.xml

 <insert id="insertStudentByMap" parameterType="java.util.Map">
        insert into t_student (id,name,age,sex,birth,height) values (null ,#{姓名},#{年龄},#{性别},#{生日},#{身高})
    </insert>

Test

   @Test
    public void testInsertStudentByMap() {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Map<String, Object> map = new HashMap<>();
        map.put("姓名", "赵六");
        map.put("年龄", 20);
        map.put("身高", 1.81);
        map.put("性别", '男');
        map.put("生日", new Date());
        mapper.insertStudentByMap(map);
        sqlSession.commit();
        sqlSession.close();
    }

运行结果截图及结论

测试运行正常。

这种方式是手动封装Map集合,将每个条件以key和value的形式存放到集合中。然后在使用的时候通过#{map集合的key}来取值。

3 实体类参数

StudentMapper接口

int insertStudentByPOJO(Student student);

StudentMapper.xml

 <insert id="insertStudentByPOJO">
        insert into t_student (id,name,age,sex,birth,height) values (null ,#{name},#{age},#{sex},#{birth},#{height})
    </insert>

Test

    @Test
    public void testInsertStudentByPOJO() {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setName("李四");
        student.setAge(30);
        student.setHeight(1.70);
        student.setSex('男');
        student.setBirth(new Date());
        int students = mapper.insertStudentByPOJO(student);
        System.out.println(students);
        sqlSession.commit();
        sqlSession.close();
    }

运行结果截图及结论

运行正常,数据库中成功添加一条数据。

这里需要注意的是:#{} 里面写的是属性名字。这个属性名其本质上是:set/get方法名去掉set/get之后的名字。

4 多参数

StudentMapper接口

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

StudentMapper.xml

<select id="selectByNameAndSex" resultType="com.powernode.mybatis.pojo.Student">
        <!--select * from t_student where name = #{arg0} and sex = #{arg1}-->
        <!--select * from t_student where name = #{param1} and sex = #{param2}-->
        select * from t_student where name = #{arg0} and sex = #{param2}
    </select>

Test

   @Test
    public void testSelectByNameAndSex() {
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectByNameAndSex("张三", '男');
        students.forEach(student -> {
            System.out.println(student);
        });
        sqlSession.close();
    }

运行结果截图及结论

通过测试可以看到:

  • arg0 是第一个参数
  • param1是第一个参数
  • arg1 是第二个参数
  • param2是第二个参数

实现原理:实际上在mybatis底层会创建一个map集合,以arg0/param1为key,以方法上的参数为value,例如以下代码:

MyBatis部分源码

Map<String,Object> map = new HashMap<>();
map.put("arg0", name);
map.put("arg1", sex);
map.put("param1", name);
map.put("param2", sex);

// 所以可以这样取值:#{arg0} #{arg1} #{param1} #{param2}
// 其本质就是#{map集合的key}

注意:使用mybatis3.4.2之前的版本时:要用#{0}和#{1}这种形式。

5 @Param注解(命名参数)

StudentMapper接口

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

StudentMapper.xml

<select id="selectByNameAndSex2" resultType="com.powernode.mybatis.pojo.Student">
        <!--select * from t_student where name = #{param2} and sex = #{param2}-->
        select * from t_student where name = #{name} and sex = #{sex}
    </select>

Test

    @Test
    public void testSelectByNameAndSex2(){
        SqlSession sqlSession = SqlSessionUntil.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.selectByNameAndSex2("张三", '男');
        students.forEach(student -> {
            System.out.println(student);
        });
        sqlSession.close();
    }

运行结果截图及结论

通过测试,一切正常。

核心:参考(4多参数)的原理@Param("这里填写的其实就是map集合的key")

  • 27
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值