前言
-
使用map的好处?
- 灵活,通过put键;给键赋值value;
- sql动态拼接的就是键(parameterType为map),可以不与实体对应
- 假设实体类,或者数据库中的表,字段或者参数过多,应当考虑使用Map;
-
区别
- Map传递参数,直接在sql中取出key即可!
parameterType="map" - 对象传递参数,直接在sql中取对象的属性即可!
parameterType="Object" - 只有一个基本类型参数的情况下,可以直接在sql中取到!
可以不写parameterType - 多个参数用Map,或者注解!
- Map传递参数,直接在sql中取出key即可!
-
示例写法:
/**
* map查询写法
* @param map
* @return
*/
User getUserByIdLike(Map<String,Object> map);
<!--map查询;key可以随意定制-->
<select id="getUserByIdLike" parameterType="map" resultType="com.mybatisstudy.pojo.User">
select * from user where id = #{id}
</select>
@Test
public void testMapSelect(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("id",3); // key可以随意定制
mapper.getUserByIdLike(map);
sqlSession.close();
}
模糊查询
- java代码执行的时候,传递通配符
%%
@Test
public void testLike(){
// 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.getUserLike("%张%");
sqlSession.close();
}
- 在sql拼接中使用通配符
<!--map模糊查询-->
<select id="getUserLike" resultType="com.mybatisstudy.pojo.User">
select * from user where name like "%"#{value}"%"
</select>