java - How to map one-to-many in Mybatis
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-17 10:07:25
0
3
539

For example, there is an entity class

public class AnswerDto{ //一个回复的类,一个问题可能会有多个回复
    int id;
    int askId;//问题id
    List<String> answers; //回复的列表
}

I originally wrote this, but it was wrong T0T, how should I map content to List<String>

<select id="getAns" parameterType="int" resultMap="uiy">
    select
    id, 
    ask_id AS "askId",
    content
    from t_answer where ask_id = #{_parameter}
</select>

<resultMap type="AnswerDto" id="uiy">
    <id property="id" column="id"/>
    <result property="askId" column="askId" />
    <collection property="ls" ofType="string">
        <constructor>
            <arg column="content"/>
        </constructor>
    </collection>
</resultMap>
曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(3)
伊谢尔伦

mybatis determines the set mapping relationship based on the <id> tag. If you must use your table, you can map it like this

<id column="askId" property="askId" />
<result column="id" property="id"/>
<collection property="answers" ofType="java.lang.String" javaType="java.util.List">
    <result column="content" />
</collection>
左手右手慢动作

The original poster should have one missing table here, which is the question table.

With the question table, the definition of DTO should be like this.

public class QuestionDTO {
     int questionId;
     String questionDesc;
     List<AnswerDTO> answers; // Answers of the question
     int created; // 创建时间
     int updated; // 更新时间
}

public class AnswerDTO{ //一个回复的类,一个问题可能会有多个回复
    int id;
    int questionId; // 问题id
    String content; // 答案内容
    int created; // 创建时间
    int updated; // 更新时间
}

At this time, there are many related query solutions for mybatis, I will attach a link.

Mybatis related query (nested query)

There is a lot of information online about mybatis related queries. You can search more.

One last suggestion, it is best not to perform related queries. The data assembly logic is placed in the code, which facilitates future DB transformation. Because as the amount of data increases, the performance of related queries is poor, and it is not easy to transform the sub-database and sub-tables. However, this is all based on the large growth of the business. At present, it would be good if the poster starts to cultivate this awareness.

给我你的怀抱

The mapping of table fields to complex object fields can be done using a custom TypeHandler.
eg:
Mapping of json fields to Java classes in MyBatis
http://www.cnblogs.com/watery...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!