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是根據(jù)<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; // 創(chuàng)建時間 int updated; // 更新時間}public class AnswerDTO{ //一個回復的類,一個問題可能會有多個回復 int id; int questionId; // 問題id String content; // 答案內(nèi)容 int created; // 創(chuàng)建時間 int updated; // 更新時間}
這個時候 mybatis 的關聯(lián)查詢解決方案有很多,我附上一個鏈接吧。
Mybatis關聯(lián)查詢(嵌套查詢)
mybatis 的關聯(lián)查詢網(wǎng)上資料蠻多的,樓主可以多搜搜。
最后提一個建議,最好不要進行關聯(lián)查詢。數(shù)據(jù)的組裝邏輯放在代碼里面來做,這樣方便以后 DB 的改造。因為隨著數(shù)據(jù)量越來越大,關聯(lián)查詢性能比較糟糕,還不容易做分庫分表的改造,不過這都是建立在業(yè)務有大量增長的情況下。當前的話,樓主開始培養(yǎng)這個意識就好啦。
回答3:表字段到復雜對象字段的映射可以采用自定義TypeHandler的方式搞定。eg:MyBatis里json型字段到Java類的映射http://www.cnblogs.com/watery...
相關文章:
1. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””2. docker - 如何修改運行中容器的配置3. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題4. docker鏡像push報錯5. 前端 - @media query 使用出現(xiàn)的問題?6. 利用IPMI遠程安裝centos報錯!7. 運行python程序時出現(xiàn)“應用程序發(fā)生異常”的內(nèi)存錯誤?8. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????9. phpstudy8.1沒集成mysql-front10. html - css氣泡,實現(xiàn)“倒三角(不知道算不算三角了)”可透明的。

網(wǎng)公網(wǎng)安備