MyBatis的输出类型类型有三种 ,分别是:输出简单类型、Map、resultMap
输出简单类型:
相应的Mapper接口
public Integer getAccountCustomer();
对应的xml中的SQL:
<select id="getAccountCustomer" resultType="Integer">
select count(*) from `customer`;
</select>
输出结果:
==> Preparing: select count(*) from `customer`;
==> Parameters:
<== Columns: count(*)
<== Row: 13
<== Total: 1
13
输出map类型:
第一种形式:key是列名,value是对应的值
public Map<String,Object> getCustomerWithId(Integer id);
<select id="getCustomerWithId" resultType="java.util.Map">
select * from `customer` where cust_id=#{id};
</select>
查询结果:
==> Preparing: select * from `customer` where cust_id=?;
==> Parameters: 7(Integer)
<== Columns: cust_id, cust_name, cust_profession, cust_phone, email
<== Row: 7, 剑圣, 刺客, 13398909088, jiansheng@163.com
<== Total: 1
{cust_profession=刺客, cust_name=剑圣, cust_id=7, cust_phone=13398909088, email=jiansheng@163.com}
第二种形式,key为指定的列,value为自定义对象‘
@MapKey("cust_id")
public Map<Integer,Customer> getAllCustomer();
要标记上注释,表名以哪一列为key
<select id="getAllCustomer" resultType="java.util.Map">
select * from `customer`
</select>
运行结果:
{1={cust_profession=射手, cust_name=鲁班, cust_id=1, cust_phone=13499887733, email=12341241@qq.com},
2={cust_profession=肉, cust_name=李白白, cust_id=2, cust_phone=18977665521, email=libai@163.com},
resultMap
如果sql查询的字段名称和pojo类中的属性名称不一致时,可以用resultMap将字段和属性名做一个对应关系
public Customer getCustomer(Integer id);
<resultMap id="customerMap" type="Customer">
<id column="cust_id" property="cust_ids"/>
<result column="cust_name" property="cust_names"/>
<result column="cust_phone" property="cust_phones"/>
<result column="cust_profession" property="cust_professions"/>
</resultMap>
<select id="getCustomer" resultMap="customerMap">
select * from `customer` where cust_id=#{id}
</select>
resultMap中的type是指要将数据库中查询的结果封装成什么对象
column值数据库中的字段 property是pojo类的属性
在sql语句上面做一个resultMap的配置,即可完成pojo类属性名称和数据库属性名称不一致时得映射