注意:这些配置在文件中的顺序非常重要!必须严格按照上图中出现的顺序定义
- setting属性
其中setting配置是所有配置中比较重要的,useGeneratedKeys,useColumnLable,mapUnderscoreToCamelcase是整合spring中比较常用的配置-
useGeneratedKeys
它的官方解释是:
允许 JDBC 支持自动生成主键,需要驱动支持。 如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能支持但仍可正常工作。(比如 Derby)
它的有效值是false|true,默认值是false。useGeneratedKeys设置为 true 时,表示如果插入的表id以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回。
useGeneratedKeys参数只针对 insert 语句生效,默认为 false; -
useColumLable
官方解释:
使用列标签代替列名。不同的驱动在这方面会有不同的表现,具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。
它的有效值是false|true,默认值是true。其实意思就是使用列别名替换列名。
列别名是数据库的知识。一个student表中有三个属性(id,name,age),就是三个列,SELECT id AS studentId
studentId就是id列的别名。 -
mapUnderscoreToCamelcase
官方解释:
是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。
有效值是true|false,默认值是false
-
参考:http://www.tianshouzhi.com/api/tutorials/mybatis/379
如果我们没有使用mapUnderscoreToCamelcase
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">;
<mapper namespace="com.tianshouzhi.mybatis.quickstart.mapper.UserMapper">
<!--定义resultMap元素-->
<resultMap id="userMap" type="com.tianshouzhi.mybatis.resultmap.User">
<id column="id" property="id" javaType="java.lang.Integer" jdbcType="INTEGER"/>
<result column="name" property="username" javaType="java.lang.String" jdbcType="VARCHAR"/>
<result column="age" property="age" javaType="java.lang.Integer" jdbcType="INTEGER"/>
</resultMap>
<!--使用resultMap属性代替resultType,其值为上面<resultType>元素的id属性值-->
<select id="testResultMap" parameterType="int" resultMap="userMap">
select id,name,age from user where id= #{id}
</select>
</mapper>
使用了mapUnderscoreToCamelcase,则可以将步骤简化为
<select id="selectById" parameterType="int" resultType="com.tianshouzhi.mybatis.quickstart.domain.User">
select id,name,register_time from user where id= #{id}
</select>
我们可以通过resultType直接指定实体类,不需要通过resultMap元素进行繁琐的配置。