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

需求:将一个表中的部分列值存入到实体的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

你可能感兴趣的:(mybatis将指定列赋值到实体的HashMap属性中)