MyBatis框架动态sql讲解(四)

128 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情

8. @Param指定参数名称

UsersMapper.java接口中:

//切换列名进行模糊查询\
//@Param("columnName"):这里定义的columnName的名称是要在xml文件中的${引用定义的名称}\
List<Users> getByColunm(@Param("columnName") String columnName,\
                     @Param("columnValue") String columnValue);

UsersMapper.xml文件中:

<select id="getByColunm" resultType="users">\
    select <include refid="columns"></include>\
    from users\
    where ${columnName} =#{columnValue}\
</select>

测试类:

@Test\
public void testGetByColumn(){\
    List<Users> list = mapper.getByColunm("username","王五四");\
    list.forEach(u-> System.*out*.println(u));\
}

9. 入参是map

入参是map,是因为当传递的数据有多个,不适合使用指定下标或指定名称的方式来进行传参,又加上参数不一定与对象的成员变量一致,考虑使用map集合来进行传递.map使用的是键值对的方式.当在sql语句中使用的时候#{键名},${键名},用的是键的名称.

UsersMapper.java接口中:

//入参是map\
List<Users> getByMap(Map<String,Date> map);

UsersMapper.xml文件中:

<select id="getByMap" parameterType="map" resultType="users">\
    select <include refid="columns"></include>\
    from users\
    where birthday between #{zarbegin} and #{zarend}\
</select>

测试类中:

@Test\
public void testGetByMap()throws Exception{\
    Date begin = new SimpleDateFormat("yyyy-MM-dd").parse("1996-01-01");\
    Date end = new SimpleDateFormat("yyyy-MM-dd").parse("1998-12-31");\
    Map<String,Date> map = new HashMap<>();\
    //放入map集合中的数据是键值对\
    map.put("zarbegin",begin);\
    map.put("zarend",end);\
    List<Users> list = mapper.getByMap(map);\
    list.forEach(u-> System.*out*.println(u));\
}

10. 返回值是map

返回值是map的适用场景,如果的数据不能使用对象来进行封装,可能查询的数据来自多张表中的某些列,这种情况下,使用map,但是map的返回方式破坏了对象的封装,返回来的数据是一个一个单独的数据, 之间不相关.map 使用表中的列名或别名做为键名进行返回数据.

10.1 map封装返回值是一行

UsersMapper.java接口中:

//返回值是一个值,是map类型,根据主键查用户对象\
Map<String,Object> getReturnMapOne(int id);

UsersMapper.xml文件中:

<select id="getReturnMapOne" resultType="map" parameterType="int">\
    select id myid,username myusername,sex mysex,address myaddress,birthday mybirthday\
    from users\
    where id=#{id}\
</select>

测试类中:

@Test\
public void testGetReturnMapOne(){\
    Map<String,Object> map = mapper.getReturnMapOne(7);\
    System.*out*.println(map);\
    System.*out*.println(map.get("username"));\
}

10.2 返回值是map多行

UsersMapper.java接口中:

//使用map封装返回多个map的集合--->List<Map<String,Object>> List<Map<String,Object>> getReturnMap();

UsersMapper.xml文件中:

    select     from users

测试类中:

@Test public void testGetReturnMap(){     List<Map<String,Object>> list = mapper.getReturnMap();     list.forEach(map-> System.out.println(map)); }

11 列名与类中成员变量名称不一致

解决方案一:

使用列的别名,别名与类中的成员变量名一样,即可完成注入。

    select bookid id,bookname name     from book

解决方案二:

使用标签进行映射。

image.png

image.png