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. JavaScript將.apply()與'new'運算符配合使用這可能嗎?2. angular.js - webpack build后的angularjs路由跳轉問題3. java - Activity中的成員變量被賦值之后,Activity被回收的時候內存才會被釋放嗎4. java - web項目中,用戶登陸信息存儲在session中好 還是cookie中好,取決于什么?5. 為什么 必須在<ul> 下建立 <li> 在建<a>?6. 請求一個數據返回內容為空或者錯誤如何再次請求幾次7. 老師,flex-shrink: 1; 按視頻操作,不會自動縮放8. 為什么bindClass訪問不了的?9. Discuz! Q 有人用過嗎?10. 我寫的哪里有錯?請大神幫忙查看一下。
