一、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实体对象属性名