文章目录
- ResultMap
- sql
- User.java
- 解决方案
- **方案一:为列名指定别名 , 别名和java实体类的属性名一致(自动映射)**
- UserMapper.xml
- UserTest.java
- 测试结果
- **方案二:使用结果集映射->ResultMap 【推荐】(手动映射)**
- 测试结果
ResultMap
ResultMap:解决属性名和字段不一致的问题
sql
在原来的user表用加入age字段
-- 在user表中添加age新字段
alter table user add column age int(3) null;
-- 更新id为1的数据年龄为18
update user set test.user.age = 18 where id = 1;
User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密码
private int userAge;//和数据库字段不同
}
UserTest.java
@Test
public void selectUserByIdTest(){
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.selectUserById(1));
session.close();
}
查询userAge为0
- select * from user where id = #{id} 可以看做 select id,name,pwd from user where id = #{id}
- mybatis会根据这些查询的列名(会将列名转化为小写,数据库不区分大小写) , 去对应的实体类中查找相应列名的set方法设值 , 由于找不到setUserAge() , 所以userAge返回0l ; 【自动映射】
解决方案
方案一:为列名指定别名 , 别名和java实体类的属性名一致(自动映射)
UserMapper.xml
<select id="selectUserById" resultType="com.sin.pojo.User" parameterType="int">
select id,name,pwd,age as'userAge' from user where id = #{id}
</select>
UserTest.java
@Test
public void selectUserByIdTest(){
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.selectUserById(1));
session.close();
}
测试结果
方案二:使用结果集映射->ResultMap 【推荐】(手动映射)
UserMapper.xml
<resultMap id="UserMap" type="com.sin.pojo.User">
<!-- id主键 -->
<id column="id" property="id"/>
<!-- property是实体类的属性名,column是数据库表的列民 -->
<result property="name" column="name"/>
<result property="pwd" column="pwd"/>
<result property="userAge" column="age"/>
</resultMap>
<select id="selectUserById" resultType="com.sin.pojo.User" parameterType="int" resultMap="UserMap">
select id,name,pwd,age from user where id = #{id}
</select>
UserTest.java
@Test
public void selectUserByIdTest(){
SqlSession session = MyBatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.selectUserById(1));
session.close();
}