【MyBatis笔记】3、属性文件,全局参数,别名,类型转换器,resultMap
优化
1.可以将配置信息 单独放入 db.properties文件中,然后再动态引入
db.properties:
k=v
<configuration>
<properties resource="db.properties"/>
引入之后,使用${key}
2.MyBatis全局参数
在conf.xml中设置
<!--
<settings>
<setting name="cacheEnabled" value="false" />
<setting name="lazyLoadingEnabled" value="false" />
</settings>
-->
3.别名 conf.xml
a.设置单个别名
b.批量设置别名
<typeAliases>
<!-- 单个别名 (别名 忽略大小写) -->
<!-- <typeAlias type="org.lanqiao.entity.Student" alias="student"/> -->
<!-- 批量定义别名 (别名 忽略大小写),以下会自动将该包中的所有类 批量定义别名: 别名就是类名(不带包名,忽略大小写) -->
<package name="org.lanqiao.entity"/>
</typeAliases>
除了自定义别名外,MyBatis还内置了一些常见类的别名。
4.类型处理器(类型转换器)
1.MyBatis自带一些常见的类型处理器
int - number
2.自定义MyBatis类型处理器
java -数据库(jdbc类型)
示例:
实体类Student : boolean stuSex
true:男
false:女
表student: number stuSex
1:男
0:女
自定义类型转换器(boolean -number)步骤:
a.创建转换器:需要实现TypeHandler接口
通过阅读源码发现,此接口有一个实现类 BaseTypeHandler ,因此 要实现转换器有2种选择:
i.实现接口TypeHandler接口
ii.继承BaseTypeHandler
类型转换器方向:
b.配置conf.xml
需要注意的问题: INTEGER
insert into student(stuno,stuname,stuage,graname,stusex) values(#{stuNo},#{stuName},#{stuAge},#{graName} ,#{stuSex ,javaType=boolean ,jdbcType=INTEGER } )
注意#{stuNo} 中存放的是 属性值,需要严格区分大小写。
resultMap可以实现2个功能:
1.类型转换
2.属性-字段的映射关系
<select id="queryStudentByStuno" parameterType="int" resultMap="studentMapping" >
select * from student where stuno = #{stuno}
</select>
<resultMap type="student" id="studentMapping">
<!-- 分为主键id 和非主键 result-->
<id property="id" column="stuno" />
<result property="stuName" column="stuname" />
<result property="stuAge" column="stuage" />
<result property="graName" column="graname" />
<result property="stuSex" column="stusex" javaType="boolean" jdbcType="INTEGER"/>
</resultMap>