Java --- mybatis解决一对一字段名与属性名的映射不一致问题

一、mybatis解决字段名与属性名的映射问题

1.1、方式一:使用字段别名的方式

/**
     * 查询所有用户信息
     * @return
     */
    List<Emp> selectByEmp();
 <!--emp_name属性名的别名empName-->
    <select id="selectByEmp" resultType="com.cjc.mybatis.entity.Emp">
        select id,emp_name empName,age,sex,email from t_emp
    </select>
 @Test
    public void test01(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> emps = mapper.selectByEmp();
        emps.forEach(emp -> System.out.println("emp = " + emp));
    }

1.2、方式二:使用mybtais的全局配置

在mybtis核心文件中配置

 <!--设置mybatis的全局配置-->
    <settings>
        <!--将下划线自动映射为驼峰如:emp_name = empName-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

映射文件 

<select id="selectByEmp" resultType="com.cjc.mybatis.entity.Emp">
        select * from t_emp
    </select>

1.3、方式三:使用resultMap解决

<!--
    父标签
    resultMap:设置自定义映射关系
    type:设置映射关系中的实体类类型
    id:唯一标识,不能重复
    子标签:
    id:设置主键的元素关系
    result:设置普通字段的映射关系
    属性:
    property:设置映射关系中的属性名,跟实体类相对应
    column:设置映射关系中的字段名,跟数据库表相对应
    -->
    <resultMap id="empResultMap" type="Emp">
        <id property="id" column="id"></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>
    <select id="selectByEmp" resultMap="empResultMap">
        select * from t_emp
    </select>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭鸭老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值