使用场景:
实现程序中属性和表中字段映射的功能(当程序中的属性和表中的字段不一致时,可以强行的映射到一起)。
【eg:】
实体类 userinfo:
@Data
public class Userinfo {
private int id;
private String name;
private String password;
private String photo; // 头像
private LocalDateTime createtime;
private LocalDateTime updatetime;
private int state;
}
mapper 里写一个标签:
<resultMap id="baseMap" type="com.example.springbootdemo4.entity.Userinfo">
<id column="id" property="id"></id>
<result column="username" property="name"></result>
<result column="password" property="password"></result>
<result column="photo" property="photo"></result>
<result column="createtime" property="createtime"></result>
<result column="updatetime" property="updatetime"></result>
<result column="state" property="state"></result>
</resultMap>
id="baseMap" -> 名称
type="com.example.springbootdemo4.entity.Userinfo" -> 映射程序中的实体类
<id column="id" property="id"></id> 主键
<select id="getAll" resultMap="baseMap">
select * from userinfo;
</select>
单元测试Mapper:
@Test
void getAll() {
List<Userinfo> list = userMapper.getAll();
System.out.println(list);
}
更简单的方法:
别名:as
mapper:
<select id="getAll" resultType="com.example.demo.entity.Userinfo">
select id,username as name,password,photo,createtime,updatetime,state from userinfo
</select>
优点:更高效;不用 select* 减少不必要的数据;保护隐私数据,不显示
总结:
当程序中的属性和数据库中的字段名不一致时的解决方案:
1、使用 resultMap 标签(在 mapper.xml 定义)
2、使用数据库别名 as 重命名(推荐)