mybatis自定义封装类型 (一)

当SQL查询出的结果集封装成bean实体时,实体类中的字段和sql结果集字段不同,不匹配的字段无法封装到实体类中。

有两种结果方法:
   1.可以在SQL语句中设置别名,进行匹配
   2.可以使用 resultMap 标签自定义封装类型
 

第一种方式设置别名就不提啦,大家都会。下面来看看resultMap标签的自定义封装

 

User表

 

User实体类

/**
 * User的实体类
 * @see  该实体类中的字段   和 数据库User表中的字段 (id,name,money) 名称不相同
 */
public class UserEntity {

  private Integer u_id;
  private String u_name;
	
  private Integer u_money;
  private String sex;
	
  //.....省略set 、 get  、toString 方法
}

 

User的持久层接口

/**
 * User表的 DAO接口
 * @author dell
 */
public interface UserMapper {
	
  //通过 id查询指定 User
  public UserEntity getUserEntityByid(Integer id);
}

 

UserMapper.xml 映射文件

<mapper namespace="com.mybatis.dao.UserMapper">

  <!-- resultMap 自定义封装规则
        id :设置封装标识       /      type:封装的类型
   -->
	<resultMap id="UsEn" type="com.mybatis.bean.UserEntity" >
	  <!-- 指定封装主键的规则
	    column :表示数据库查询的结果集对应的字段
            prorerty : 指定对应对象的字段名
	  -->
	  <id column="id" property="u_id"/>
	
           <!-- 指定普通字段的封装规则 -->
	  <result column="name"  property="u_name" />
	  <result column="money"  property="u_money" />
	   <!-- 其余没有指定的字段,mybatis会自动封装(前提是数据库字段和实体类字段一样)
		但是建议只要定义resultMap就建议全部定义好) -->
           <!-- 还有sex字段,实体类和数据库字段名都一样,可以不指定,但是建议指定 -->
	  <result column="sex" property="sex"/>
	</resultMap>



	<!-- public User getUserEntityByid(Integer id); -->
	<select id="getUserEntityByid" resultMap="UsEn">  <!-- 返回值使用 自定义封装规则-->
		select * from User where id = #{id} 
	</select>
</mapper>

 

main

public static void main(String[] args) throws IOException {
		
	String resource = "mybatis_config.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new 
     SqlSessionFactoryBuilder().build(inputStream);
		
	SqlSession session = sqlSessionFactory.openSession();
	UserMapper mapper = session.getMapper(UserMapper.class);
		
	UserEntity entity = mapper.getUserEntityByid(1);  //查询id为1 的User
	System.out.println(entity.toString());
}

 

console 输出

 UserEntity [u_id=1, u_name=tom, u_money=1200, sex=man]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值