数据类型别名
在持久层映射文件中 ParameterType 属性指定参数类型,ResultType 属性指定结果集类型。数据类型可以是基本数据类型,引用数据类型,自定义数据类型。MyBatis 给基本数据类型、引用数据类型都注册了别名,当数据类型是以上两种时可以使用别名,映射关系如下表:
别名 | 数据类型 |
---|---|
_byte | byte |
_long | long |
_short | short |
_int | int |
_integet | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
integer | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
bigdecimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
MyBatis 也提供了给自定义数据类型注册别名的方式,在 SqlMapConfig.xml 核心配合文件中进行相应的配置,当数据类型是自定义数据类型也可以使用别名。
<typeAliases>
<!-- 单个别名定义 -->
<typeAlias alias="user" type="chu.yi.bo.domain.User"/>
<!-- 批量别名定义,扫描整个包下的类,别名为类名(首字母大小写均可) -->
<package name="chu.yi.bo.domain"/>
</typeAliases>
<select id="findByName" resultType="user" parameterType="string">
select * from user where username like '%${value}%';
</select>
ResultMap 配置映射关系
使用 MyBatis 进行查询操作,ResultType 属性指定参数类型为自定义数据类型,POJO 的属性名必须与数据库表的字段称一致,如果不一致可以使用 ResultMap 标签建立映射关系。
<resultMap type="chu.yi.bo.domain.User" id="userMap">
<id column="id" property="userId"/>
<result column="name" property="userName"/>
<result column="sex" property="userSex"/>
</resultMap>
<select id="findByName" resultType="userMap" parameterType="string">
select * from user where username like '%${value}%'
</select>
Id 标签用于建立主键字段的映射关系,Result 标签用于建立非主键字段的映射关系。Column 属性指定数据库字段名,Property 属性指定 POJO 属性名。