13、Mybatis查询结果映射

一、 配置下滑线映射成驼峰

可以使用配置后的自动映射方法,但是需要满足一定的规则,若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性名符合Java的规则(使用驼峰)。此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系

可以在MyBatis的核心配置文件中的setting标签中,设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰,例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName。核心配置文件详解;

    

二、 resultMap结果映射

mybatis在通常情况下根据属性名称会自动映射,但是如果字段名和属性名不一致,需要使用结果映射。可以采用别名和resultMap两种方式;

第一种:

1.先定义resultMap标签,指定列名和属性名称对应关系;

2.在select标签使用resultMap属性,指定上面定义的resultMap的id值,该id和查询的resultMap="StudentMpa"一一对应;

resultMap可以只针对没有映射上的关系进行人工映射,不过最好对全部字段进行映射;

/** * 查询所有学生信息 * @return */public  List selectStudentByIds(String ids);
                      
@Testpublic    void selectStuByIds() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);    String ids = "('2', '3', '4')";    List studentList = mapper.selectStudentByIds(ids);    studentList.forEach(student -> System.out.println(student));}

注意:resultType和resultMap不能同时使用。

三、 查询结果使用别名

使用列别名,让别名和Java对象属性名称一样,这样可以直接封装到对象中;

/** * 查询所有学生信息 * @return */public  List selectStudentByIds(String ids);
@Testpublic    void selectStuByIds() {    SqlSession sqlSession = MybatisUtils.getSqlSession();    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);    String ids = "('2', '3', '4')";    List studentList = mapper.selectStudentByIds(ids);    studentList.forEach(student -> System.out.println(student));}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章