Mybatis的类型别名指的是我们可以为Java类型自定义一个简短的名字,以达到简化配置的目的,在上篇博文中我们的sql语句配置文件内容如下:
<?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="User">
<select id="queryUserInfoByName" parameterType="string" resultType="com.mybatis.domain.User">
select * from User where username = #{username}
</select>
<insert id="saveUser" parameterType="com.mybatis.domain.User">
insert into user(username,password,phone) values(#{username},#{password},#{phone});
</insert>
<update id="updateUser" parameterType="com.mybatis.domain.User">
update user set password=#{password} where username=#{username}
</update>
<delete id="deleteUser" parameterType="com.mybatis.domain.User">
delete from user where username = #{username}
</delete>
</mapper>
可以看到一些标签的resultType和parameterType属性值为com.mybatis.domain.User
,我们可以为这种类型定义一个简单一点的名字,比如就叫user。
具体做法非常简单,打开mybatis数据源配置文件SqlMapConfig.xml,通过typeAliases标签来完成:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 自定义类型别名 -->
<typeAliases>
<typeAlias alias="user" type="com.mybatis.domain.User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="User.xml"/>
</mappers>
</configuration>
以下部分为类型别名的配置:
<typeAliases>
<typeAlias alias="user" type="com.mybatis.domain.User"/>
</typeAliases>
有了这个类型别名,我们就可以对上节的sql配置文件进行调整,使用到com.mybatis.domain.User
的地方 可以全部替换为user:
<?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="User">
<select id="queryUserInfoByName" parameterType="string" resultType="user">
select * from User where username = #{username}
</select>
<insert id="saveUser" parameterType="user">
insert into user(username,password,phone) values(#{username},#{password},#{phone});
</insert>
<update id="updateUser" parameterType="user">
update user set password=#{password} where username=#{username}
</update>
<delete id="deleteUser" parameterType="user">
delete from user where username = #{username}
</delete>
</mapper>