Mybatis 全局配置文件中typeAliases(别名)

 在具体的mapper.xml文件中,定义很多的statement,statement需要parameterType指定输入参数的类型、需要resultType指定输出结果的映射类型。

  如果在指定类型时输入类型全路径,不方便进行开发,可以针对parameterType或resultType指定的类型定义一些别名,在mapper.xml中通过别名定义,方便开发。


一.mybatis默认支持别名

别名

映射的类型

_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


如下图所示:int就是别名;



二.自定义别名

  单个定义别名

 使用typeAliases标签,定义别名;将cn.itcast.mybatis.po.User 起别名为user;

[html]  view plain  copy
  1.        <!-- 别名定义 -->  
  2. <typeAliases>  
  3.     <!-- 针对单个别名定义 type:类型的路径 alias:别名 -->  
  4.     <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/>  
  5. </typeAliases>  

  批量定义别名

  mybatis自动扫描包中的po类,自动定义别名,别名是类名(首字母大写或小写都可以,一般用小写)

  例如:cn.itcast.mybatis.po.User起别名为User或者user;

[html]  view plain  copy
  1. <!-- 别名定义 -->  
  2. <typeAliases>  
  3.     <!-- 批量别名定义,指定包名,mybatis自动扫描包中的po类,自动定义别名,别名是类名(首字母大写或小写都可以,一般用小写) -->  
  4.     <package name="cn.itcast.mybatis.po" />  
  5. </typeAliases>  

在mapper.xml文件中

  没有定义别名前

[html]  view plain  copy
  1. <select id="findUserById" parameterType="int"  
  2.     resultType="cn.itcast.mybatis.po.User">  
  3.     select * from USER where id = #{id}  
  4. </select>  

  定义别名后,直接resultType中使用别名user;

[html]  view plain  copy
  1. <select id="findUserById" parameterType="int"  
  2.     resultType="user">  
  3.     select * from USER where id = #{id}  
  4. </select>  

三.总结:

  使用别名就像数据库中的别名一样,简化了我们的操作,可以用简单的名词,单词对象的整个路径。操作起来更加方便,清晰;

转载自:http://blog.csdn.net/fxq8866/article/details/52635153?foxhandler=RssReadRenderProcessHandler

猜你喜欢

转载自blog.csdn.net/menghuannvxia/article/details/79640566