好处
- 当实体类或数据库中的表,字段或者参数过多时,应该使用map
比如根据年龄、名字、地址查id,接口中的方法就可能会写成:
List<> getId(int age,String name,String address);
- 至于mapper.xml由于是多参数那么就不能使用parameterType, 改用#{index}是第几个就用第几个的索引,索引从0开始,如果参数多了就会搞不清楚0、1、2是什么意思。
<select id="geId" resultType="List<>">
select id from tableName where age = #{0} and name = #{1} and address = #{2}
</select>
如果改成Map
-
List getId(Map<String, Object> map);
-
mapper.xml如下:
<select id="geId" resultType="List<>">
<!-- 参数名随便写 -->
select id from tableName where age = #{age001} and name = #{name002} and address = #{addre}
</select>
- test一下
public class PeopleDAOtest {
@Test
public void test007(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("age001",1);
map.put("name002","老王");
map.put("addre","火星");
peopleMapper.getId(map);
}
}
模糊查询
- java中拼接
%王%
如:
List<> lis = mapper.getLike("%王%");
- 在sql语句中
<select id="getLike" resultType="com.mybatis.pojo.People">
select * from mybatis.people where name like "%"#{value}"%";
</select>
- 二者选其一