javabean的属性名和表的字段名不一致的情况 ---- 结果集映射

javabean的属性名和表的字段名不一致的情况 ---- 结果集映射

javabean的属性名与表的字段名不一致有两种解决办法

方法一 查询时使用别名

<select id="selectEmpLikeEname" parameterType="string"  resultType="Emp">
    select  empno no ,ename name ,job,hiredate,sal from emp where ename like concat("%",#{ename},"%");
</select>

方法二 使用结果集映射

可以使用结果映射resultMap来建立映射关系,完成有字段到属性的映射,达到将查询结果封装为对象的目的。resultMap是对resultType的增强

<resultMap/>标签中定义了type指定的类的属性名到表中字段名称的映射关系。根据这个映射关系,框架利用反射机制创建相应的对象。

  • type:指定要映射的实体类
  • id:指定该resultMap映射关系的名称
  • <id>标签;id的字段名column与实体类的实行property间的映射关系
  • <result>标签:id以外其他字段名column与实体类的属性property间的映射关系,当然,对于字段名与实体类的属性名相同的情况,可以不写入<resultMap/>中

实例

 <resultMap id="empMap" type="employee">
        <id column="empno" property="no"></id>
        <result column="ename" property="ename"></result>
        <result column="job" property="job"></result>
        <result column="hiredate" property="hiredate"></result>
        <result column="sal" property="sal"></result>
 </resultMap>

<select id="selectEmpLikeEnaem" parameterType="string" resultMap="empMap">
        select * from emp where ename like concat("%",#{ename},"%")
</select>
发布了41 篇原创文章 · 获赞 1 · 访问量 892

猜你喜欢

转载自blog.csdn.net/DreamCloud714/article/details/104596196