准备1、查询一个实体类对象
mapper接口映射文件测试输出结果 2、查询一个list集合
mapper接口映射文件测试输出结果 3、查询单个数据
mapper接口映射文件测试输出结果 4、查询一条数据为map集合
mapper接口映射文件测试输出结果 5、查询多条数据为map集合
方式一:List
mapper接口映射文件测试输出结果 方式二:@MapKey注解
mapper接口映射文件测试输出结果
准备数据库表
t_person表
实体类对象
通过name=“王五”进行查询一条数据,并封装在Person对象中。
mapper接口public interface PersonMapper {
//通过name查询对象
Person selectPersonByName(@Param("name") String name);
}
映射文件
测试
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Person zs = mapper.selectPersonByName("张三");
System.out.println(zs);
输出结果
2、查询一个list集合
查询所有age=20的人。
mapper接口public interface PersonMapper {
//查询所有age=20的人
List selectPersonByAge(@Param("age") Integer age);
}
映射文件
测试
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
List people = mapper.selectPersonByAge(20);
System.out.println(people);
输出结果
3、查询单个数据
查询年龄等于xx的人的个数。
mapper接口public interface PersonMapper {
//查询年龄等于20的人的个数
Integer selectAgeCount(Integer age);
}
映射文件
测试
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
//查询年龄是20岁的人的个数
Integer integer = mapper.selectAgeCount(20);
System.out.println(integer);
输出结果
4、查询一条数据为map集合
根据用户name查询用户信息为map集合。
mapper接口public interface PersonMapper {
//根据用户name查询用户信息为map集合
Map selectPersonByIdMap(@Param("name")String name);
}
映射文件
测试
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
//根据用户name查询用户信息为map集合
Map map = mapper.selectPersonByIdMap("王五");
System.out.println(map)
输出结果
5、查询多条数据为map集合
查询所有用户信息为map集合。
将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此 时可以将这些map放在一个list集合中获取。
public interface PersonMapper {
//查询所有用户信息为map集合01。
List
映射文件
测试
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
//查询所有用户信息为map集合01
List
输出结果
方式二:@MapKey注解
将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并 且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的 map集合。
mapper接口public interface PersonMapper {
//查询所有用户信息为map集合02。
@MapKey("name")
Map selectAllPerson02();
}
映射文件
测试
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
//查询所有用户信息为map集合02
Map maps = mapper.selectAllPerson02();
System.out.println(maps);
输出结果



