nhmicro框架Map与bean映射(orm机制)

nhmicro框架中dao层操作为了保证灵活性和可扩展性,输入输出均为map,但开发人员比较熟悉使用bean作为dao层输入输出。使用micro-orm.jar中的MicroBeanMapUtil和MicroMappingAnno实现map与bean相互映射。维持灵活性的同时,也向开发人员编程习惯靠拢,并间接实现了编译时字段约束和检查。

 

Bean中使用@MicroMappingAnno说明map对应的key

public class TestBean {

 

@MicroMappingAnno(name="user_id")  

private Integer userId;

 

@MicroMappingAnno(name="user_name")

private String userName;

 

@MicroMappingAnno(name="user_age"

private Integer userAge;

 

public Integer getUserId() {

    return userId;

}

public void setUserId(Integer userId) {

    this.userId = userId;

}

public String getUserName() {

    return userName;

}

public void setUserName(String userName) {

    this.userName = userName;

}

public Integer getUserAge() {

    return userAge;

}

public void setUserAge(Integer userAge) {

    this.userAge = userAge;

}

 

 

}

 

代码中使用MicroBeanMapUtil.beanToMap将bean转为map,使用MicroBeanMapUtil.mapToBean将map转为bean,注意map中的值均为string类型。

    public static void main(String[] args) throws Exception {

        TestBean testBean=new TestBean();

        testBean.setUserAge(20);

        testBean.setUserId(123);

        testBean.setUserName("tom");

        Map beanMap=MicroBeanMapUtil.beanToMap(testBean);

        System.out.println("bean to map="+beanMap);

       

        Map paramMap=new HashMap();

        paramMap.put("user_id", "678");

        paramMap.put("user_name", "jerry");

        paramMap.put("user_age", "33");

        TestBean mapBean=(TestBean) MicroBeanMapUtil.mapToBean(paramMap, TestBean.class);

        System.out.println("map to bean="+mapBean);

    }

 

你可能感兴趣的:(nhmicro框架Map与bean映射(orm机制))