Mybatis: 一对多(多对多)结果集

2022-08-22 07:56:34

xml映射文件:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.heiketu.testpackage.mapper.VendorsMapper"><!--结果集一对多或多对多--><resultMapid="manyToMany"type="com.heiketu.testpackage.pojo.Vendor"><idcolumn="vend_id"property="vendId"/><resultcolumn="vend_name"property="vendName"/><resultcolumn="vend_address"property="vendAddress"/><resultcolumn="vend_city"property="vendCity"/><resultcolumn="vend_state"property="vendState"/><resultcolumn="vend_zip"property="vendZip"/><resultcolumn="vend_country"property="vendCountry"/><!--链表子结果集--><collectionproperty="productList"ofType="com.heiketu.testpackage.pojo.Product"><idcolumn="prod_id"property="prodId"/><resultcolumn="vend"property="vendId"/><resultcolumn="prod_name"property="prodName"/><resultcolumn="prod_desc"property="prodDesc"/></collection></resultMap><selectid="getResultManyToMany"resultMap="manyToMany">
      select
         v.*,
         p.prod_id,
         p.vend_id vend,
         p.prod_name prod_name,
         p.prod_desc prod_desc
      from Vendors v,Products p where v.vend_id = p.vend_id and v.vend_id = #{vendorId}</select></mapper>

映射接口:

publicinterfaceVendorsMapper {//数据一对多或多对多关系
    Vendor getResultManyToMany(@Param("vendorId") String vendorId);
}

测试文件:

 SqlSession sqlSession =null;try {
    String configFile ="mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(configFile);
    SqlSessionFactory build =new SqlSessionFactoryBuilder().build(inputStream);
    sqlSession = build.openSession();//以一对多的结果形式返回
    VendorsMapper mapper = sqlSession.getMapper(VendorsMapper.class);
    Vendor vendor = mapper.getResultManyToMany("FNG01");
    System.out.println(vendor);

}catch (IOException e) {
    e.printStackTrace();
}finally {
    sqlSession.close();
}

结果:

Vendor{vendId='FNG01', vendName='Fun and Games', vendAddress='42 Galaxy Road', vendCity='London', vendState='null', vendZip='N16 6PS', vendCountry='England'}

mybatis获取结果集一对多或多对多,可以使用resultMap的collection。通过指定collection,获取对应的实体类的子结果集。

collection标签中需指定俩个属性:property属性指定对应的子结果集在实体类中的属性名,ofType属性指定每个子结果集的对象类型。

  • 作者:走路的猫头鹰
  • 原文链接:https://blog.csdn.net/u014268482/article/details/80613322
    更新时间:2022-08-22 07:56:34