返回顶部

收藏

mybatis ResultHandler 示例

更多

有些sql查询会返回一些复杂类型,这些复杂类型没有办法简单的通过xml或者注解配置来实现,这种时候我们需要实现mybatis 的ResultHandler接口,来做自定义的对象属性映射。

ResultHandler例子:

Mybatis在调用ResultHandler的handleResult(ResultContext)方法之后生成bean,首先我们定义一个复杂对象。

public interface GrandFatherMapper {
    public static class GrandFatherWithGrandChildren {
        public GrandFather grandFather;
        public Child child;
    }
    public void selectComplex(ResultHandler handler);
}

然后我们创建一个mapper:

<mapper namespace="ca.qc.ircm.examples.resulthandler.GrandFatherMapper">
    <resultMap id="ComplexMap" type="ca.qc.ircm.examples.resulthandler.GrandFatherMapper$GrandFatherWithGrandChildren">
          <association property="grandFather" javaType="GrandFather">
            <id property="id" column="GrandFather_id"/>
            <result property="name" column="GrandFather_name"/>
          </association>
          <association property="child" javaType="Child">
            <id property="id" column="Child_id"/>
            <result property="name" column="Child_name"/>
          </association>
    </resultMap>
    <select id="selectComplex" resultMap="ComplexMap">
          SELECT GrandFather.id AS GrandFather_id, GrandFather.name AS GrandFather_name, Child.id AS Child_id, Child.name AS Child_name
          FROM GrandFather
          JOIN Father ON GrandFather.id = Father.grand_father_id
          JOIN Child ON Father.id = Child.father_id
    </select>
</mapper>

然后我们在selectComplex方法中使用自定义的handler,并得到处理之后的结果:

    public Map<GrandFather, List<Child>> selectGrandFathersWithChildren() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            class MyResultHandler implements ResultHandler {
                Map<GrandFather, List<Child>> grandFatherWithChildren = new HashMap<GrandFather, List<Child>>();
                @Override
                public void handleResult(ResultContext context) {
                    final GrandFatherWithGrandChildren complex = (GrandFatherWithGrandChildren)context.getResultObject();
                    if (!grandFatherWithChildren.containsKey(complex.grandFather)) {
                        grandFatherWithChildren.put(complex.grandFather, new ArrayList<Child>());
                    }
                    grandFatherWithChildren.get(complex.grandFather).add(complex.child);
                }
            };
            MyResultHandler handler = new MyResultHandler();
            GrandFatherMapper grandFatherMapper = sqlSession.getMapper(GrandFatherMapper.class);
            grandFatherMapper.selectComplex(handler);

            return handler.grandFatherWithChildren;
        } finally {
            sqlSession.close();
        }
    }

标签:java,mybatis,orm

收藏

0人收藏

支持

0

反对

0

发表评论