使用场景:
实现程序中属性和表中字段映射的功能(当程序中的属性和表中的字段不一致时,可以强行的映射到一起)。
【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 重命名(推荐)
本文介绍了在Java程序中,当属性与数据库字段不匹配时如何通过resultMap标签进行映射,以及使用数据库别名提高查询效率和保护隐私的方法。推荐使用别名来避免`select*`,只获取所需字段。
&spm=1001.2101.3001.5002&articleId=132522200&d=1&t=3&u=808f5673b75b44f782aa5aa05110746c)
1030

被折叠的 条评论
为什么被折叠?



