概述
在MyBatis中, 很多地方我们需要配置全限定类名
, 比如com.example.entity.Role
就是一个全限定类名. 而这样的重复配置会让我们的文件看起来很长,所以我们可以配置一些别名, 在Mapper文件中直接使用别名.
注册别名的两种方法
方法1: 在configuration中配置typeAliases节点.
// mybatis-cfg.xml
<configuration>
<!-- 配置别名, 可以在resultType或者parameterType用别名代替全路径名-->
<typeAliases>
<!-- alias参数是指别名, 而type则是类型的全限定名 -->
<typeAlias alias="role" type="com.example.entity.Role"/>
<typeAlias alias="myStringHandler" type="com.example.handler.MyStringTypeHandler"/>
</typeAliases>
</configuration>
方法2: 在configuration文件中配置typeAliases节点, 但是在对应的类上加上@Alias
注解
// mybatis-cfg.xml
<configuration>
<!-- 配置别名, 可以在resultType或者parameterType用别名代替全路径名-->
<typeAliases>
<!-- 注意: 现在只需要配置全限定类名, 而别名使用@Alias注解在对应的类上 -->
<typeAlias type="com.example.entity.Role"/>
<typeAlias type="com.example.handler.MyStringTypeHandler"/>
</typeAliases>
</configuration>
// com.example.handler.MyStringTypeHandler
@Alias("myStringTypeHandler")
public class MyStringTypeHandler implements TypeHandler<String> {}
// com.example.entity.Role
@Alias(value = "role")
public class Role {}
在Mapper映射文件中使用别名
// RoleMapper.xml
<?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.example.mapper.RoleMapper">
<resultMap id="roleMap" type="role">
<id column="id" property="id" javaType="long" jdbcType="BIGINT"/>
<result column="role_name" property="roleName" javaType="string"/>
<result column="note" property="note" typeHandler="myStringTypeHandler"/>
</resultMap>
<select id="getRole" parameterType="long" resultMap="roleMap">
select id, role_name as roleName, note from t_role where id = #{id}
</select>
<insert id="insertRole" parameterType="role">
insert into t_role(role_name, note) values(#{roleName}, #{note})
</insert>
<delete id="deleteRole" parameterType="long">
delete from t_role where id=#{id}
</delete>
</mapper>
我们可以看到在insert的parameterType属性使用了role
这个别名, 代替了com.example.entity.Role
在resultMap的节点中, 使用myStringTypeHandler
代替了com.example.handler.MyStringTypeHandler
.
MyBatis的TypeAliasRegistry
别名如何工作的呢? 在MyBatis中, 它将别名都注册到了TypeAliasRegistry
中, 我们使用别名的时候, 会自动检索出来全限定类型. 部分代码如下所示
public class TypeAliasRegistry{
private final Map<String, Class<?>> TYPE_ALIASES = new HashMap<String, Class<?>>();
public TypeAliasRegistry() {
registerAlias("string", String.class);
registerAlias("byte", Byte.class);
registerAlias("long", Long.class);
registerAlias("short", Short.class);
registerAlias("int", Integer.class);
registerAlias("integer", Integer.class);
registerAlias("double", Double.class);
registerAlias("float", Float.class);
registerAlias("boolean", Boolean.class);
...