Heim  >  Fragen und Antworten  >  Hauptteil

java – Wie man in Mybatis eine Eins-zu-Viele-Zuordnung erstellt

Zum Beispiel gibt es eine Entitätsklasse

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

Ich habe das ursprünglich geschrieben, aber es war falsch. T0T, wie soll ich Inhalte der Liste<String> zuordnen?

<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>
曾经蜡笔没有小新曾经蜡笔没有小新2712 Tage vor538

Antworte allen(3)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-05-17 10:09:25

    mybatis是根据<id>标签确定集合映射关系的, 如果一定要用你这个表的话可以这样映射

    <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>

    Antwort
    0
  • ringa_lee

    ringa_lee2017-05-17 10:09:25

    楼主这里应该还少了一张表,就是问题表。

    配合问题表,DTO的定义应该是这样的。

    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; // 更新时间
    }

    这个时候 mybatis 的关联查询解决方案有很多,我附上一个链接吧。

    Mybatis关联查询(嵌套查询)

    mybatis 的关联查询网上资料蛮多的,楼主可以多搜搜。

    最后提一个建议,最好不要进行关联查询。数据的组装逻辑放在代码里面来做,这样方便以后 DB 的改造。因为随着数据量越来越大,关联查询性能比较糟糕,还不容易做分库分表的改造,不过这都是建立在业务有大量增长的情况下。当前的话,楼主开始培养这个意识就好啦。

    Antwort
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-17 10:09:25

    表字段到复杂对象字段的映射可以采用自定义TypeHandler的方式搞定。
    eg:
    MyBatis里json型字段到Java类的映射
    http://www.cnblogs.com/watery...

    Antwort
    0
  • StornierenAntwort