成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

java - Mybatis 一對多怎么映射

瀏覽:117日期:2023-11-30 09:23:31

問題描述

比如有一個實體類

public class AnswerDto{ //一個回復的類,一個問題可能會有多個回復 int id; int askId;//問題id List<String> answers; //回復的列表}

java - Mybatis 一對多怎么映射

我原本這么寫,但是是錯的 T0T, 應該如何將content映射到List<String>

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

問題解答

回答1:

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>回答2:

樓主這里應該還少了一張表,就是問題表。

配合問題表,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 的改造。因為隨著數據量越來越大,關聯查詢性能比較糟糕,還不容易做分庫分表的改造,不過這都是建立在業務有大量增長的情況下。當前的話,樓主開始培養這個意識就好啦。

回答3:

表字段到復雜對象字段的映射可以采用自定義TypeHandler的方式搞定。eg:MyBatis里json型字段到Java類的映射http://www.cnblogs.com/watery...

標簽: java
相關文章: