Loading

mybatis 全局typeAliases配置(配置别名)

什么是typeAliases配置,有什么用

一个简单的例子

<mapper namespace="com.kehao.mapper.UserMapper">
   <select id="queryUserById" parameterType="Integer" resultType="com.kehao.pojo.User">
      select * from user where id=#{id}
  </select>
</mapper>

可以看到 resultType 这里配置的是全类名 非常麻烦 有很多个mapper的话 每一个都要配置 非常繁琐
我们希望用一个别名user去替代com.kehao.pojo.User,达到配置的简化,这就是typeAliases配置别名的作用

自带的一些别名

别名 映射的类型
_byte byte
_long long
_short short
_int int
_integer 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
map Map

自己配置别名

单独配置别名

结果集数据类型定义别名,别名不区分大小写

<typeAliases>
    <!-- 为pojo对象定义别名-->
    <typeAlias type="com.kehao.pojo.User" alias="user"></typeAlias>
</typeAliases>
<!-- 使用别名即可-->
<select id="queryUserById" parameterType="int" resultType="User">
   select * from user where id=#{id}
</select>

像刚才的 JavaBean,User 是放在 cn.com.kehao.pojo 包里的,包里可能也会存在其他多个 JavaBean,这时候一个一个配置别名就会很麻烦,这时候就需要批量定义别名,批量指定很简单,只要指定包名即可,之后程序会为包下的所有类都自动加上别名,其定义别名的规范就是对应包装类的类名首字母变为小写,其示例代码如下:

批量配置别名

<typeAliases>
    <!--<typeAlias type="com.kehao.pojo.User" alias="user"></typeAlias>-->
    <!-- 自动扫描pojo包下的全部类-->
    <package name="com.kehao.pojo" ></package>
</typeAliases>

这时设置的包名下的类就都有了别名,别名就是类名(首字母小写),像刚才的 User 类,其别名就为 user。

注解配置别名

除了在配置文件中单独的配置别名和批量的配置别名两种方式外,还有一种方式,就是通过注解的方式来配置别名,方法也很简单,在需要配置别名的类前通过 @Alias 注解即可,参数就是别名名称,例如以下示例代码:

@Alias("user")
public class User{
    //其他代码
}
posted @ 2021-03-25 22:39  克豪  阅读(315)  评论(0)    收藏  举报