Mybatis七(自定义结果映射规则)

之前在遇到Javabean属性与数据库字段对应不起来的时候我们有两种解决方法,

  1. 在sql语句中为数据库字段起别名,使之与Javabean属性对应起来
  2. 在mybatis的主配置文件中开启驼峰命名法,只要你的命名规则符合驼峰命名规则,mybatis就会为你做相应的匹配

现在我们有了第三种方法,也就是这里要介绍的自定义结果映射规则.


主配置文件

将驼峰命名法关闭

<settings>
    <setting name="mapUnderscoreToCamelCase" value="false" />
</settings>

接口

public Employee selectEmpById2(Integer id);

配置文件

使用resultMap方法自定义结果规则映射

<mapper namespace="com.fish.dao.EmployeeMapper">
<!-- resultMap:
    自定义某个Javabean的封装规则
    type:自定义规则的java类型
    id:唯一的id 方便引用
 -->
<resultMap type="com.fish.pojo.Employee" id="emp">
<!-- id:
    指定主键列的封装规则
    id定义主键底层有优化
    column:指定那一列
    property:指定对应的Javabean属性
 -->
    <id column="id" property="id" />
    <!-- 定义普通列封装规则 -->
    <result column="last_name" property="lastName" />
    <!-- 其他不指定的列会自动封装;一般我们写resultMap会把所有的都写上 方便检查 -->
    <result column="email" property="email" />
    <result column="gender" property="gender" />
</resultMap>
<!-- 使用resultMap -->
<select id="selectEmpById2" resultMap="emp">
    select * from tbl_employee where id = #{id}
</select>

 

测试代码

@org.junit.Test
public void test01() throws IOException {
    //读取配置文件
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //获取SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession openSession = sqlSessionFactory.openSession();
    //调用getMapper方法获取该接口的实现类
    EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
    Employee selectEmpById = mapper.selectEmpById2(1);
    System.out.println(selectEmpById);
    //关闭Session
    openSession.close();

}

运行结果

Employee [id=1, lastName=222, email=ZFH_FISH@163.COM, gender=1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值