02-MyBatis_当实体属性与表字段名不一致

0. 源码下载

    MyBatis表字段名与实体属性名不一致-src.zip

1. 场景:


    当实体属性与表字段名不一致

 ① 实体 

public class User {

    private String id;
    private String username;
    private String uaddress;

    // set/get 已省略
}
 
 ② 表
+-----------+-------------
| Field      | Type       
+-----------+-------------
| id           | varchar(36)
| name     | varchar(64)
| address | varchar(128) 
+-----------+--------------


2. 解决方案

   - SQL语句中给字段取别名, 别名与实体属性名一致

   - 使用映射, 类似于Hibernate


 2.1 方案一  别名
    <select id="selectAllUsers" resultType="xxx.domain.User">
        select id as id, name as username, address as uaddress  
        from user

    </select> 

 2.2 方案二 映射

/*
<!-- 将表字段与实体属性一一对应 -->
<resultMap type="com.hehe.mybatis.domain.User" id="userMap">
	<id column="id" property="id"/>
	<result column="name" property="username"/>
	<result column="address" property="uaddress"/>
</resultMap>

<select id="selectUserById" parameterType="string" resultMap="userMap">
	select * from user where id = #{id}
</select>	
*/	@Test public void testSelectUserById() throws Exception {
		SqlSession session = sqlSessionFactory.openSession();

		User user = session.selectOne("com.hehe.mybatis.domain.User.selectUserById", "0001");
		System.out.println(user);
		
		session.close();
	}





相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页