需求:
在mapper.xml中,定义很多的statement,statement需要parameterType指定输入参数的类型、需要resultType指定输出结果的映射类型。
如果在指定类型时输入类型全路径,不方便进行开发,可以针对parameterType或resultType指定的类型定义一些别名,在mapper.xml中通过别名定义,方便开发。
在mybatis的开发中, 实体类对应的映射xml配置文件(比如UserMapper.xml等)里面的sql语句(比如:
<select id="findUserByid" parameterType="int" resultType="store.cloudspace.pojo.User">
SELECT * FROM USE WHERE id = #{id}
</select>
)都需要有输入/输出参数类型(上面的parameterType/resultType)。其中前者完整的写法应该是:parameterType="java.lang.Integer",但是在这里mybatis已经自动转换了,mybatis支持自动的类型有:
别名 | 映射的类型 |
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 |
所以入参的类型一般不需要我们转换,但是输出参数的类型却需要我们做一些事情,因为输出参数大部分是某个包里面的实体类型。那么,我们该如何自定义这些类型呢?
在配置文件(SqlMapConfig.xml)按照如下格式写:
<!-- 定义别名,方便开发(返回、输出类型写成:store.cloudspace.pojo.User 不方便开发) -->
<typeAliases>
<!-- 单个别名自定义 -->
<!-- <typeAlias type="store.cloudspace.pojo.User" alias="user"/>-->
<!-- 批量自定义别名
指定包名,mybatis自动扫描包中的pojo类,自动定义别名,别名就是类名(首字母大小写都可以) -->
<package name="store.cloudspace.pojo" />
<package name="store.cloudspace.xxx" />
<!--如有需要自定义多个文件,只需要写多个
<package name="store.cloudspace.pojo" />即可
-->
</typeAliases>
注意上面的:指定包名,mybatis自动扫描包中的pojo类,自动定义别名,别名就是类名(首字母大小写都可以)
也就是说,映射文件里面的resultType的类型我们只要写对应类名即可,如:resultType=“user”;