mybatis 一对多关系 list 的返回

配置映射文件

<resultMap id="BaseResultMap" type="com.xxx.model.xxx" >

    <!--
      WARNING - @mbggenerated
    -->
 
    <id column="USERID" property="userid" jdbcType="VARCHAR" />
    <result column="ADDTIME" property="addtime" jdbcType="TIMESTAMP" />
    <result column="ISDISABLE" property="isdisable" jdbcType="DECIMAL" />
    <result column="ISTOP" property="istop" jdbcType="DECIMAL" />
    <result column="SORTCODE" property="sortcode" jdbcType="DECIMAL" />
    <collection column="USERID" property="itemList"  javaType="List"  ofType="com.xxx.model.Items" select="geItemsById"/>

  </resultMap>


  <select id="geItemsById" parameterType="String" resultType="com.xxx.model.Items">
    select * from  table where USERID=#{USERID}
  </select>


实体类


    @Column(name = "ISDISABLE")
    private Short isdisable;


    @Column(name = "ISTOP")
    private Short istop;


    @Column(name = "SORTCODE")
    private Integer sortcode;


    @Column(name = "INTRODUCE")
    private String introduce;


    //*****该对象对应的集合*****begin*****//      @Transient  -实体bean中所有的非static非@Transient都可以被持久化,除非你将其注解为@Transient。
    @Transient    
    private List<Items> itemList=new ArrayList<Items>();


    public List<Items> getItemList(){
    return itemList;
    }
    public void setItemList(List<Items> itemList){
    this.itemList=itemList;
    }

Mybatis是一个优秀的持久层框架,它支持多种关系映射方式,包括一对一、一对多、多对一、多对多等。下面举一个一对多关系映射的例子: 假设我们有两个表:学生表(student)和课程表(course),一个学生可以选修多门课程,因此在课程表中需要保存学生的id。我们可以通过Mybatis进行一对多关系映射。 首先我们需要定义两个Java类:Student和Course,然后在Student类中定义一个List<Course>类型的属性,用于保存学生所选修的课程。在Course类中定义一个Student类型的属性,用于保存选修该课程的学生信息。 接下来,在Mybatis的Mapper.xml文件中编写SQL语句,可以使用Mybatis的association和collection标签来实现一对多关系映射。具体操作如下: 1. 首先查询学生表,将学生信息和对应的课程id一并查询出来。 2. 然后根据查询出来的课程id查询课程表,将查询出来的课程信息赋值给Course对象。 3. 将Course对象添加到List<Course>属性中。 4. 最后返回Student对象,即可完成一对多关系映射。 以下是Mapper.xml文件的示例代码: ``` <!-- 查询学生信息和对应的课程id --> <select id="getStudent" parameterType="int" resultType="Student"> SELECT * FROM student WHERE id = #{id} </select> <!-- 根据课程id查询课程信息 --> <select id="getCourseByStudentId" parameterType="int" resultType="Course"> SELECT * FROM course WHERE student_id = #{studentId} </select> <!-- 定义一对多关系映射 --> <resultMap id="studentMap" type="Student"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> <collection property="courses" ofType="Course"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="teacher" property="teacher"/> </collection> </resultMap> ``` 使用以上配置,在调用Mapper接口时,即可获取到包含学生信息和所选修的课程信息的Student对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值