typeAliases标签和package标签
# 130.typeAliases标签和package标签
如题,讲解下这两个标签的作用
# typeAliases
之前我们写delete标签的时候,说过parameterType
可以写int,INT,Integer,INTEGER(不区分大小写),java.lang.Integer等,而resultType不行,必须得严格按照要求来:
<select id="findById" parameterType="INT" resultType="com.peterjxl.domain.User">
select * from user where id = #{uid}
</select>
1
2
3
2
3
为什么parameterType
可以这么随意呢?这是因为Mybatis起了别名,所以就不区分大小写,例如当解析到int,INT时,都知道是int类型。而我们也可以在SqlMapConfig.xml里配置别名:
<properties resource="jdbcConfig.properties"/>
<typeAliases>
<typeAlias type="com.peterjxl.domain.User" alias="user"/>
</typeAliases>
1
2
3
4
2
3
4
type属性指定的是实体类全限定类名。alias属性指定别名。注意typeAliases标签得在properties标签后面定义。
当指定了别名,就不再区分大小写了。我们可以在select标签里直接用:
<!-- 根据QueryVo的条件查询用户-->
<select id="findUserByVo" parameterType="com.peterjxl.domain.QueryVo" resultType="USER">
select * from user where username like #{user.userName}
</select>
1
2
3
4
2
3
4
# package标签
实际项目中,一个包下面有很多很多的类,如果每个都是用alias配置,就很麻烦;此时我们可以用package标签简化。
<typeAliases>
<!-- <typeAlias type="com.peterjxl.domain.User" alias="user"/>-->
<package name="com.peterjxl.domain"/>
</typeAliases>
1
2
3
4
2
3
4
当指定包的名称后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写,
在mappers标签里,也可以定义package,指定dao接口所在的包,这样就不用逐个指定配置文件了:
<mappers>
<!--<mapper resource="com/peterjxl/dao/IUserDao.xml"/>-->
<!--<mapper class="com.peterjxl.dao.IUserDao"/>-->
<package name="com.peterjxl.dao"/>
</mappers>
1
2
3
4
5
2
3
4
5
当指定了之后就不需要在写mapper以及resource或者class了
注意,在typeAliases标签里写的是实体类的包名,在mappers标签里写的是dao接口所在的包名
# 源码
本文所有代码已上传到了GitHub (opens new window)和Gitee (opens new window)上,并且创建了分支demo12,读者可以通过切换分支来查看本文的示例代码。
在GitHub上编辑此页 (opens new window)
上次更新: 2023/5/6 21:54:08