在开发中我们经常会遇到实体类属性采用驼峰命名,而数据库中使用下划线_进行分隔,从而导致了实体类中属性名和数据库中的字段名不对应:
在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);