字段名与属性名不一致时的处理

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

mybatis学习记录
06. MyBatis 字段名与属性名不一致时的处理


提示:以下是本篇文章正文内容,下面案例可供参考

创建MySQL表

mybatis库,新建t_dept表(字段:int:did(主键),varchar: dept_name);
新建t_emp表(字段:int:eid(主键),varchar: emp_name,int:age,varchar: sex,varchar: email,int:did)

创建相应实体类

/**
 * @Description: 部门信息实体类
 * @Author: zqf
 * @Date: 2022/3/2 14:49
 * @Version 1.0
 **/
public class Dept {
    private Integer did;
    private String deptName;
    private List<Emp> emps;

//有参无参构造,Getter,Setter,toString()省略
}
/**
 * @Description: 员工信息实体类
 * @Author: zqf
 * @Date: 2022/3/2 14:49
 * @Version 1.0
 **/
public class Emp implements Serializable {
    private Integer eid;
    private String empName;
    private Integer age;
    private String sex;
    private String email;
    private Dept dept;
    
//有参无参构造,Getter,Setter,toString()省略
}

字段名与属性名不一致时的处理

测试方法:

	@Test
    public void testGetAllEmp() {
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> list = mapper.getAllEmp();
        list.forEach(emp -> System.out.println(emp));
    }

mapper接口:

public interface EmpMapper {
	List<Emp> getAllEmp();
}	
  • a>通过设置字段名别名,与属性名一致

 映射文件:

    <!--List<Emp> getAllEmp();-->
	<select id="getAllEmp" resultType="Emp">
    	select eid,emp_name empName,age,sex,email from t_emp
	</select>
  • b>通过mybatis-config设置全局配置mapUnderscoreToCamelCase设为true,将_自动映射为驼峰

 映射文件:

    <!--List<Emp> getAllEmp();-->
	<select id="getAllEmp" resultType="Emp">
        select * from t_emp
	</select>

mybatis全局配置:
通过mybatis-config设置全局配置mapUnderscoreToCamelCase设为true,将_自动映射为驼峰

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
  • c>通过resultMap设置自定义映射关系
     子标签:id设置主键的映射关系,result设置普通字段映射关系
     resultMap:设置自定义映射(通常用于处理一对多或多对一的映射关系)
       属性:
         id:表示自定义映射的唯一标识
         type:查询的数据要映射的实体类的类型
       子标签:
         id:设置主键的映射关系
         result:设置普通字段的映射关系
         association:设置多对一的映射关系
         collection:设置一对多的映射关系
       属性:
         property:设置映射关系中实体类中的属性名
         column:设置映射关系中表中的字段名,必须是sql语句查询出来的字段名

 映射文件:

    <resultMap id="empResultMap" type="Emp">
        <id property="eid" column="eid"></id>
        <result property="empName" column="emp_name"></result>
        <result property="age" column="age"></result>
        <result property="sex" column="sex"></result>
        <result property="email" column="email"></result>
    </resultMap>
    
    <!--List<Emp> getAllEmp();-->
    <select id="getAllEmp" resultMap="empResultMap">
        select * from t_emp
    </select>

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值