java - Mybatis 一對多怎么映射
問題描述
比如有一個實體類
public class AnswerDto{ //一個回復的類,一個問題可能會有多個回復 int id; int askId;//問題id List<String> answers; //回復的列表}
我原本這么寫,但是是錯的 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...
相關文章:
1. mysql - 新浪微博中的關注功能是如何設計表結構的?2. android-studio - Android Studio 運行項目的時候一堆警告,跑步起來!?3. MySQL數據庫中文亂碼的原因4. angular.js使用$resource服務把數據存入mongodb的問題。5. 如何解決Centos下Docker服務啟動無響應,且輸入docker命令無響應?6. angular.js - 關于$apply()7. dockerfile - [docker build image失敗- npm install]8. 表單提交驗證,沒反應,求老師指點9. angular.js - Ionic 集成crosswalk后生成的apk在android4.4.2上安裝失敗???10. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?
