【SSM】MyBatis(八.参数处理)

文章目录

  • 1.准备数据
  • 2.单个简单类型参数
  • 3.Map参数
  • 4.实体类参数
  • 5.多参数
  • 6.@Param注解(命名参数)

1.准备数据

【SSM】MyBatis(八.参数处理)_第1张图片

【SSM】MyBatis(八.参数处理)_第2张图片

2.单个简单类型参数

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

<mapper namespace="com.sdnu.mybatis.mapper.StudentMapper">
    <select id="selectById" resultType="Student" parameterType="long">
        select * from t_student where id = #{id}
    select>
    <select id="selectByName" resultType="Student" parameterType="String">
        select * from t_student where name = #{name, javaType=String, jdbcType=VARCHAR}
    select>
    <select id="selectByBirth" resultType="Student" parameterType="Date">
        select * from t_student where birth = #{birth}
    select>
    <select id="selectBySex" resultType="Student" parameterType="char">
        select * from t_student where sex = #{sex}
    select>
mapper>

3.Map参数

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

4.实体类参数

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

5.多参数

    <select id="selectByNameAndSex" resultType="Student">
        select * from t_student where name = #{arg0} AND sex = #{arg1}
--         等同于select * from t_student where name = #{param0} AND sex = #{param1}
    select>

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}

6.@Param注解(命名参数)

StudentMapper.java

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

StudentMapper.xml

    <select id="selectByNameAndSex2" resultType="Student">
        select * from t_student where name = #{name} AND sex = #{sex}
    select>

mybatis部分源码:

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

你可能感兴趣的:(SSM,mybatis,java,数据库)