Mybatis的实体类别名设置
<select>中的resultType属性用于绑定实体类
通常情况下绑定实体类需要输入完整的实体类路径,如下:
<mapper namespace="org.momo.mapper.StudentMapper">
<select id="queryStudentByNo" parameterType="int" resultType="org.momo.entity.Student">
select *
from student
where stu_no = #{stuNo}
</select>
</mapper>
但当多个实体类需要导入时使用起来麻烦,所以我们为resultType设置一个简单的别名
在映射文件中添加<typeAliases>,alias就是实体类的别名,如下:
<typeAliases>
<typeAlias type="org.momo.entity.Student" alias="student"/>
</typeAliases>
别名设置好后,就可以将resultType的内容从完整的路径改为“student”
<mapper namespace="org.momo.mapper.StudentMapper">
<select id="queryStudentByNo" parameterType="int" resultType="student">
select *
from student
where stu_no = #{stuNo}
</select>
</mapper>
但是会发现另外一个问题,一般情况下,实体类不止一个,那么有没有办法将entity中的实体类一次性全部设置别名呢?
答案是可以的,我们只需将typeAliases中的typeAlias改为package,如下:
<typeAliases>
<package name="org.momo.entity"/>
</typeAliases>
此时resultType的内容同样可以使用别名,并且此时的别名与实体类类名相同,不区分大小写