Timbo Site

write something


MyBatis Collection Query

昨天和同事在讨论ORM工具的查询方案,希望拉取一个表中的一行数据,用Object A来装,A中有个List<Object B>,B是A的某个字段在另一张表内字段,希望通过ORM工具把这多行数据抽出来组成List<Object B>

现在的ORM工具,无论全自动和半自动的都有现成的解决方案了,只是今天在讨论组里正好有人在问这个问题,于是晚上回来试试MyBatis


第一件事就是找MyBatis的文档,在MyBatis简介里面就有提到

###动手试一试

####先建表

dbuser表

one2many-postgresql-table

usercomment的uid与dbuser的id关联,拉取多条数据

####建ORM Object

#####User

    Long id
    String name
    List<UserComment> comments

#####UserComment

    Long id
    String uid
    String comment

####Mapper文件中

    <resultMap id="user" type="user">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <collection property="comments" column="id" ofType="userComment" select="getCommentByUid"/>
    </resultMap>
    <resultMap id="comment" type="userComment">
        <result property="id" column="id"/>
        <result property="uid" column="uid"/>
        <result property="comment" column="comment"/>
    </resultMap>
    <select id="getAllUsers" resultMap="user">
        SELECT * FROM DBUSER ORDER BY ID ASC
    </select>
    <select id="getCommentByUid" resultMap="comment">
        SELECT * FROM USERCOMMENT WHERE UID = #{id}
    </select>

resultMap中定义一个collectioncollection中定义的select,用column与上一级查询的字段进行关联,就可以将另一个查询结果塞入定义的Java Collection类型中,MyBatis能自动识别类型,也能通过设置javaType的值进行指定

测试一下,当拉取User的时候,可以将UserComment拉出来

one2many-debug

####是可以用,但

可以这么用,但和两次查询后拼接对象差不多,反而只需要拉取User不需要UserComment,会额外多出一次查询

还是NoSQL好啊还是NoSQL好啊还是NoSQL好啊