`

mybatis之类似级联功能的使用( 转)

 
阅读更多
在spring+mybatis开发中,经常会遇到需要子列表查询的时候,hibernate中对于级联查询应用得比较多,它本身自带的一对多,多对一等映射可以完整的实现级联。在mybatis中,没有级联的概念,但是可以利用集合来实现类似的功能。下面就来看下具体的用法。
这里以product产品为例。
一个产品可以包含多条评论。这时就可以利用mybatis中的集合来实现。
首先简历product的bean类
public class Product  implements Serializable{

  
    private static final long serialVersionUID = 1L;
    private int id;
    private int productTypeId;
    private String name;
    private String description;
    private List<Comment> comments; //所以相关评论列表
    。。。。//以下get set方法略
}
然后建立评论的bean类,这里省略。。。
下面就是在产品类的ProductMapper.xml中配置映射关系。
首先写个返回类型
<resultMap type="Product" id="result_product">
        <result property="id" column="id"/>
        <result property="productTypeId" column="product_type_id"/>
        <collection property="comments" column="id" select="com.bjk.apes.dao.CommentMapper.getCommentByProductId"/>
    </resultMap>
其中collection就表示返回的comment列表类型。

然后在select中键入这个resultMap
<select id="getProductById" resultMap="result_product" parameterType="String">
       select *
       from product
       where id=#{id}
    </select>

这样返回的product对象中就包含了所有的评论。是不是和hibernate一样方便啊。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics