比如有一個實體類
public class AnswerDto{ //一個回復(fù)的類,一個問題可能會有多個回復(fù)
int id;
int askId;//問題id
List<String> answers; //回復(fù)的列表
}
我原本這么寫,但是是錯的 T0T, 應(yīng)該如何將content映射到List<String>
<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>
mybatis是根據(jù)<id>
標簽確定集合映射關(guān)系的, 如果一定要用你這個表的話可以這樣映射
<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>
樓主這里應(yīng)該還少了一張表,就是問題表。
配合問題表,DTO的定義應(yīng)該是這樣的。
public class QuestionDTO {
int questionId;
String questionDesc;
List<AnswerDTO> answers; // Answers of the question
int created; // 創(chuàng)建時間
int updated; // 更新時間
}
public class AnswerDTO{ //一個回復(fù)的類,一個問題可能會有多個回復(fù)
int id;
int questionId; // 問題id
String content; // 答案內(nèi)容
int created; // 創(chuàng)建時間
int updated; // 更新時間
}
這個時候 mybatis 的關(guān)聯(lián)查詢解決方案有很多,我附上一個鏈接吧。
Mybatis關(guān)聯(lián)查詢(嵌套查詢)
mybatis 的關(guān)聯(lián)查詢網(wǎng)上資料蠻多的,樓主可以多搜搜。
最后提一個建議,最好不要進行關(guān)聯(lián)查詢。數(shù)據(jù)的組裝邏輯放在代碼里面來做,這樣方便以后 DB 的改造。因為隨著數(shù)據(jù)量越來越大,關(guān)聯(lián)查詢性能比較糟糕,還不容易做分庫分表的改造,不過這都是建立在業(yè)務(wù)有大量增長的情況下。當前的話,樓主開始培養(yǎng)這個意識就好啦。
表字段到復(fù)雜對象字段的映射可以采用自定義TypeHandler的方式搞定。
eg:
MyBatis里json型字段到Java類的映射
http://www.cnblogs.com/watery...