MyBatis 输出类型

MyBatis的输出类型类型有三种 ,分别是:输出简单类型MapresultMap

输出简单类型:

相应的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类属性名称和数据库属性名称不一致时得映射

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值