mybatis将指定列赋值到实体的HashMap属性中

本文介绍如何使用MyBatis将数据库表的部分列值存入实体类的HashMap属性中。通过配置mapper.xml文件实现address和telephone列的值映射到TestMap实体类的attributes属性。
需求:将一个表中的部分列值存入到实体的HashMap属性中
表结构: 
/*
Navicat MySQL Data Transfer

Source Server Version : 50533

Target Server Type    : MYSQL
Target Server Version : 50533
File Encoding         : 65001

Date: 2013-11-01 15:34:47
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `TEST_MAP`
-- ----------------------------
DROP TABLE IF EXISTS `TEST_MAP`;
CREATE TABLE `TEST_MAP` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(20) DEFAULT NULL,
  `address` varchar(100) DEFAULT NULL,
  `telephone` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of TEST_MAP
-- ----------------------------
INSERT INTO `TEST_MAP` VALUES ('1', 'name1', 'address1', '1111');
INSERT INTO `TEST_MAP` VALUES ('2', 'name2', 'address2', '2222');

实体类:

import java.util.Map;

public class TestMap {
    private Integer id;
    private String name;
    private Map<String, String> attributes;//将address和telephone的值放入其中
    
    
    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

    public Map<String, String> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, String> attributes) {
		this.attributes = attributes;
	}

	public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

}


mapper.xml配置:

<resultMap id="BaseResultMap" type="cn.com.china.entity.TestMap" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <id column="name" property="name" jdbcType="VARCHAR" />
   <association property="attributes" javaType="java.util.HashMap" >
	    <id column="address" property="address" jdbcType="VARCHAR" />
	    <id column="telephone" property="telephone" jdbcType="VARCHAR" />
   </association> 
  </resultMap>

配置:
<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->  
<setting name="autoMappingBehavior" value="PARTIAL" />

测试类:

public class TestMapServiceTest extends BaseTest {
	TestMapMapper testMapMapper = null;

	@Before
	public void setUp() {
		testMapMapper = (TestMapMapper) ctx.getBean(TestMapMapper.class);
	}

	@Test
	public void select() {
		TestMap map = testMapMapper.selectByPrimaryKey(1);
		System.out.println("name:"+map.getName());
     	System.out.println("name:"+map.getAttributes().get("name"));
		System.out.println("address:"+map.getAttributes().get("address"));
		System.out.println("telephone:"+map.getAttributes().get("telephone"));
	}

}

测试结果:
name:name1
name:null
address:address1
telephone:1111

转载于:https://my.oschina.net/ydsakyclguozi/blog/173500

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值