Mybatis-实体类属性名与数据库字段名不同的查询方法

来源:互联网 发布:淘宝联盟怎么刷流量 编辑:程序博客网 时间:2024/05/05 04:47

查询语句是 MyBatis 中最常用的元素之一,本文涉及mybatis的单表查询操作,关联表有关的查询会后续补充。

  巧妇难为无米之炊,要想从数据库中表中取出数据并转化为javaBean,所以,我们要先准备javabean以及与其对应的数据表。

javaBean:

public class President {private int id;private String name;@Overridepublic String toString() {return "President [id=" + id + ", name=" + name + "]";}       //get set 方法.....}
创建两个对应的数据库表,并插入两条数据:

create table president1(    p_id int not null auto_increment primary key,    p_name varchar(50) not null);insert into president1(p_name) values('lily'),('Tom');create table president2(    id int not null auto_increment primary key,    name varchar(50) not null);insert into president2(name) values('lily'),('Tom');
创建两个数据库是为了测试两个不同的查询状况,

数据库字段名与实体类属性名相同

从sql表可以看出president2的字段名与javabean:President的属性名完全相同,这种情况下mybatis的select操作非常简单:
<!-- 从表 president2中查询--><select id="getPreByIdPresident2" parameterType="int" resultType="President">select * from president2 where id=#{id}</select>
此时mybatis运用反射机制会将查询返回的结果(id,name)封装成President对象。

如果从表president1中查询,同样采用上面的sql语句
<!-- 从表 president1中查询--><select id="getPreByIdPresident1" parameterType="int" resultType="President"><span style="white-space:pre"></span>President p1 = session.selectOne(statement+"getPreByIdPresident1", 1);<span style="white-space:pre"></span>System.out.println("表president1中查询"+p1);</select>
此时如果用getPreByIdPresident1进行查询,返回的结果会是null,我们将上面的sql语句在mysql中执行下:

有结果返回,但是返回的字段名为(p_id,p_name)这种结果mybatis在解析时无法与President类对应。多数情况下实体类属性名与数据库表的字段名都会有差异,这种情况如果mybatis不能处理也就太low了。

数据库字段名与实体类属性名不相同

mybatis针对该种情况有两种解决方法,但是归根到底都是同一种实现。

Method1:定义一个ResultMap将数据库字段名与实体类属性名做个映射

我们欲从表president1中查询数据,此时的mapper配置如下:
<resultMap type="President" id="getFromPresident2"><!-- 主键必须用id标签映射,其他的用非集合用result映射 集合类用collection映射 --><!-- column为数据库字段名,property为实体类属性名 --><id column="p_id" property="id" /><result column="p_name" property="name" /></resultMap><select id="getPreByIdPresident1Method1" resultMap="getFromPresident2">select * from president1 where p_id=#{id}</select>
首先定义了一个resultMap,将数据库表的字段名与实体类属性名做了一一对应,其中type为实体类(此处运用的类别名),id为了在select标签中引用映射结果。
在select标签中并没有用resultType属性,而使用了resultMap,即为上面定义的resultMap,mybatis会根据resultMap中的映射关系去构造President

Method1:直接在sql语句中使用别名

<!-- 从表 president1中查询 --><select id="getPreByIdPresident1Method2" resultType="President">select p_id id,p_name name from president1 where p_id=#{id}</select>
这种方法会查到实际的数据,这种方法与字段名和属性名相同都是基于相同的原理:MyBatis 会在幕后自动创建一个 ResultMap,基于属性名来映射列到JavaBean 的属性上。即mybatis底层都是通过创建ResultMap来进行关系的映射,与method1原理相同。。

上面用到的测试用例的源码地址:用例源码

1 0