喝绿茶的猫 2020-02-21
1.我们都知道,在mybatis中写实体类的时候,是按照数据库中的列名来给实体类定义属性的,举个例子:
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
}
2.但是,如果我们在定义实体类的时候,实体类中的属性与数据库列名不一致呢?比如:
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;
}3.这个时候就有两种解决办法:
方法一:在sql语句中给数据库中的字段起别名:
<select id="findAll" resultType="com.itheima.domain.User">
select id as userId, username as userName,birthday as userBirthday,sex as userSex,address as userAddress from user ;
</select>这样就能够把查询到的数据与实体类的属性对应起来,并封装回User类的对象了,缺点是每次都要起别名,消耗精力,优点是执行效率高。
方法二:给实体类和数据库建立对应关系:
<resultMap id="userMap" type="com.itheima.domain.User">
<!-- 主键字段的对应-->
<id property="userId" column="id"></id>
<!-- 非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
<result property="userAddress" column="address"></result>
</resultMap>然后在sql语句中将resultType设置为"userMap"即可;
<!-- 查询所有-->
<select id="findAll" resultType="userMap">
select * from user ;
</select>这种方法写起来代码量少,但是因为添加了resultMap对应这一环节,执行效率不高。