mybatis文件映射之自定义返回结果集

时间:2022-07-23
本文章向大家介绍mybatis文件映射之自定义返回结果集,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、select还有以下属性:

2、自动映射

3、使用resultMap

mybatis-conf.xml配置文件中,需要把settings标签放在properties之后,environments之前,不然会报错。由于数据库字段last_name和java属性lastName不匹配。有三种解决方式,一种是在查询的时候取别名,第二种是配置驼峰命名法,配置之后会自动将数据库中的带有下划线的字段映射为lastName。第三种是自己利用resultMap自定义结果返回集,在其中进行映射。

在一般情况下,我们使用resultType作为标识返回值,例如:

在EmployeeMapper.java中

public Employee getEmpById(Integer id);

在EmployeeMapper.xml中

    <select id="getEmpById" resultType="com.gong.mybatis.bean.Employee">
        select * from tbl_employee where id=#{id}
    </select>

现在我们要自己定义返回结果,可在EmployeeMapper.xml中进行修改

    <resultMap type="com.gong.mybatis.bean.Employee" id="MyEmp">
        <id column="id" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="gender" property="gender"/>
        <result column="email" property="email"/>
    </resultMap>
    <select id="getEmpById" resultMap="MyEmp">
        select * from tbl_employee where id=#{id}
    </select>

说明:在resultMap标签中,type指明返回的类型,id属性用于标识该resultMap,其中的id标签为主键所对应的标签,result标签中的为普通字段,column是数据库中的字段,property是Java中属性的名称,如果数据库中的字段名与java中的属性的类型的名字不一致,那么就需要进行配置,相同则可以不必配置,Mybatis会自动进行配置。