Mybatis的对象封装

常用的对象封装方法:

1、封装主键

<id property="id" column="id" />

2、封装基础类型属性

<result property="questionContent" column="question_content" />
3、封装其他类的对象
<association property="questionType" javaType="com.lonelyzhe.springboot.bean.QuestionType">
    <id property="id" column="type_id"/>
    <result property="type" column="type"/>
</association>

4、封装其他类型的对象的集合(此可用于一对多关系的查询)

  1. property:为该类中,有关其他类对象的属性名
  2. column:数据库中对应的字段,在本类型中的,用于在select查询方法中传参
  3. ofType:该集合中的对象类型,最好不用resultMap
  4. javaType:该集合的类型
  5. select:即将使用该方法根据column的值去查询的集合
<collection property="tags"
            column="id" 
            ofType="com.lonelyzhe.springboot.bean.QuestionTag"
            javaType="ArrayList" 
            select="getTagsByQuestionId"/>
<resultMap id="questionResult" type="com.lonelyzhe.springboot.bean.Question">
    <id property="id" column="id" />
    <result property="questionContent" column="question_content" />
    <result property="questionAnalyse" column="question_analyse" />
    <result property="questionAnswer" column="question_answer" />
    <result property="goodNumber" column="good_number"/>
    <association property="owner" javaType="com.lonelyzhe.springboot.bean.Mine">
        <id property="id" column="owner_id"/>
        <result property="nickName" column="nickname"/>
        <result property="describe" column="describe"/>
        <result property="image" column="image"/>
    </association>
    <association property="questionType" javaType="com.lonelyzhe.springboot.bean.QuestionType">
        <id property="id" column="type_id"/>
        <result property="type" column="type"/>
    </association>
    <association property="hardness" javaType="com.lonelyzhe.springboot.bean.Hardness" >
        <id property="id" column="hardness_id" />
        <result property="hardness" column="hardness" />
    </association>
    <association property="student" javaType="com.lonelyzhe.springboot.bean.Student" >
        <id property="id" column="student_id" />
        <result property="student" column="student" />
    </association>
    <!--要使用ofType,最好不要用resultMap,用bean类-->
    <collection property="tags" column="id" ofType="com.lonelyzhe.springboot.bean.QuestionTag"
        javaType="ArrayList" select="getTagsByQuestionId"/>
</resultMap>
发布了98 篇原创文章 · 获赞 21 · 访问量 6416

猜你喜欢

转载自blog.csdn.net/qq_42396168/article/details/105099965