MyBatis使用resultMap映射结果集、MyBatis解决对象属性名和数据库字段名不一致

一、MyBatis自动映射功能

1.MyBatis提供了自动映射功能,只需要返回的SQL列名和Java实体对象属性一致就行了。在我们实际开发中,我的数据库列名规范大都是要求每个单词用下划线分隔,而JAVA实体则是用驼峰命名法,于是使用MyBatis自动映射,或直接在配置文件中开启驼峰命名方式。

2.例如

实体对象属性如下

public class Account{

    private String id;

    private String name;

    private double money;

    private Date created = new Date();

    private Date updated = new Date();

    private Integer isdeleted = 0;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }

    public Integer getIsdeleted() {
        return isdeleted;
    }

    public void setIsdeleted(Integer isdeleted) {
        this.isdeleted = isdeleted;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", created=" + created +
                ", updated=" + updated +
                ", isdeleted=" + isdeleted +
                '}';
    }
}

数据库表列名:

 mapper映射语句:

<select id="sel" resultType="yuan.yuanmybatis.entity.Account">
       select id,name,created,updated,isdeleted from account where id = #{id}
    </select>

Dao接口:

@Repository
public interface AccountMapper {

    Account sel(String id);
}

 测试:

 @Test
    public void testResultMap(){
       Account account= accountMapper.sel("1");
        System.out.println(account.toString());
    }

 

二、Mybatis使用resultMap映射结果集

1、当需要处理复杂的映射时,使用MyBatis的自动映射就力不从心了,这时候我们就可以使用resultMap了。

2、如下

<resultMap id="BaseResultMap" type="yuan.yuanmybatis.entity.Account">
        <id column="id" jdbcType="VARCHAR" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="money" jdbcType="DOUBLE" property="money" />
    </resultMap>

   <select id="sel" resultMap="accountResultMap">
       select id,name,money from account where id = #{id}
    </select>

解释一下resultMap的配置

2.1、id为定义了一个唯一标识,type对应的java实体对象

2.2、id表情定义java实体id即主键,result标签定义java实体对象其他属性,column属性为数据库列名,property属性为对应的java实体对象属性名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值