Mybatis学习--14.查询专题
#####自定义结果集映射
可以在mapper.xml文件中通过resultMap标签自定义一个结果映射集resultmap,用来指定pojo类的属性和数据库表的字段之间的对应关系。解决了我们编写查询sql语句时需要给字段名重命名的麻烦。
该标签中有两个重要属性:
- id:用于唯一标识该映射集
- type:指定对应的pojo类
<mapper namespace="com.deng.mybatis.mapper.StudentMapper"> <resultMap id="studentResultMap" type="student" > <!--为了提高mybatis效率,建议加上数据库表的主键,即使主键字段名和pojo类属性名一致--> <id property="id" column="id"></id> <result property="name" column="name"></result> <result property="age" column="age"></result> <result property="date" column="date"></result> <result property="height" column="height"></result> <result property="gender" column="gender"></result> </resultMap> <select id="selectById" resultMap="studentResultMap"> select * from t_student where id = #{id}; </select> </mapper>
1
2
3
4
5
6
7
8
9
##### Mybatis中开启自动驼峰映射
* 可以在mybatis核心配置文件中进行配置,使我们查询结果时,pojo类的属性名可以直接映射为对应的数据库表的字段名。
* ```xml
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>不过这种方法是有前提条件的:pojo类属性的命名和数据库表字段的命名都需要符合规范。pojo类属性名需要符合驼峰命名法,数据库表的字段名必须全部小写,单词之间用下划线分隔。比如pojo类中的studentName对应字段名studeng_name
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 dch'blog!