解决MyBatis开发中实体类属性名和数据库中字段名不对应问题

在开发中我们经常会遇到实体类属性采用驼峰命名,而数据库中使用下划线_进行分隔,从而导致了实体类中属性名和数据库中的字段名不对应:
数据库中的字段通常使用 _ 进行分隔
在java代码中,我们通常使用驼峰命名的方式

public class Staff {
    private Integer id;
    private String name;
    private String gender;
    private String salary;
    private Date joinDate;
    private Integer depId;
    ......
    }

分为两种情况: 基于xml配置文件 基于注解开发
一:基于xml配置文件
1.给sql起别名,让其查询出的字段与实体类中的属性名相同:

    <select id="showAll" resultType="Staff">
        select id,name,gender,salary,join_date as joinDate,dep_id as depId from emp;
    </select>

运行结果正常,但是这个方式是极不方便的,可以使用sql标签进行优化:

    <sql id="all">
        id,name,gender,salary,join_date as joinDate,dep_id as depId
    </sql>
    <select id="showAll" resultType="Staff">
        select <include refid="all"></include> from emp;
    </select>

虽然可以使用sql标签每次引入,提高一定的复用性,但是依然很不方便
2.使用resultMap:
我们可以在mapper文件中定义一个resultMap标签,正如标签名一样,它像一个map,将数据库中的字段名和实体类中的属性名一一对应,并且指定返回的数据类型,像是功能升级版的resultType

    <resultMap id="resultStaff" type="Staff">
        <result column="NAME" property="name"/>
        <result column="join_date" property="joinDate"/>
        <result column="dep_id" property="depId"/>
    </resultMap>

在后续的的代码中,只要涉及到该类型就可以通过resultMap的id调用啦:

    <select id="showAll" resultMap="resultStaff">
        select * from emp;
    </select>

二:基于注解的MyBatis开发:
使用注解开发可以使我们的开发更加便捷,适合一些简单的sql语句
解决属性名和数据库中字段名不对应问题也与基于xml开发如出一辙:
1.给sql语句起别名

    @Select("select id,name,gender,salary,join_date as joinDate,dep_id as depId from emp")
    List<Staff> showAll();

2.使用@ResultMap:
基于注解开发,并没有xml中的resultMap标签怎么办? MyBatis为我们提供了注解@Results,@Result,@ResultMap用来代替mapper文件中的<resultMap>,<result>,<select id="showAll" resultMap="id">
具体的实现方式也是很好理解:

    @Select("select * from emp")
    @Results({
            @Result(column="join_date",property="joinDate"),
            @Result(column="dep_id",property="depId")
    })
    List<Staff> showAll();

但是这只是解决了当前方法的问题,怎么让后面的代码复用呢? 就像<resultMap>标签一样,@Results同样具有一个id属性,后面的代码就能通过@ResultMap(“id”)来复用该代码了:

    @Select("select * from emp")
    @Results(id = "reStaff",value={
            @Result(column="join_date",property="joinDate"),
            @Result(column="dep_id",property="depId")
    })
    List<Staff> showAll();

    @Select("select * from emp where id=#{id}")
    @ResultMap("reStaff")  //这里直接使用@ResultMap引入就好啦~
    Staff selectById(int id);
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值