MyBatis關(guān)聯(lián)映射
查詢多個表數(shù)據(jù),然后封裝成復(fù)雜對象。(帶有關(guān)聯(lián)的對象)
XML SQL定義
1.需要使用元素定義查詢結(jié)果和對象屬性映射
2.需要使用或指定加載一個還是多個記錄
Direction表(類別) Subject表(學(xué)科)
一個類別可以對應(yīng)多個學(xué)科,一個Direction對應(yīng)多個Subject。
查詢類別及其包含多個學(xué)科信息,可以封裝成下面結(jié)構(gòu)的Direction
public class Direction{
private int id;
private String name;
private List<Subject> subjects;//實體類中定義一個集合subjects
}
然后定義XML SQL(方法一:用一個多表查詢一次性取出所需數(shù)據(jù))
<resultMap id="directionMap" type="cn.xdl.Direction">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="subjects" ofType="cn.xdl.Subject"> --resultmap里面寫上集合屬性subject 類型寫實體類 字段補齊
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="direction_id" property="directionId"/>
</collection>
</resultMap>
--寫好resultMap一次性查完
<select id="findDirectionAndSubjects" resultMap="directionMap">
select *
from direction d
join subject s on (d.id=s.direction_id)
</select>
然后定義XML SQL(方法二:用多個查詢語句取出所需數(shù)據(jù))
<select id="findDirectionAndSubjects" resultMap="directionMap">
select *
from direction
</select>
<resultMap id="directionMap" type="cn.xdl.Direction">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="subjects" ofType="cn.xdl.Subject"
select="cn.xdl.dao.SubjectMapper.findByDirectionId">
</collection>
</resultMap>
//在SubjectMapper定義一個findByDirectionId查詢
<select id="findByDirectionId" resultType="cn.xdl.Subject">
select * from subject
where direction_id=#{direction_id}
</select>
注解 SQL定義
注解SQL只提供了上述方法二的實現(xiàn),由多個單表查詢語句取出所需數(shù)據(jù)。
使用@Results、@ResultMap ,等價于< resultMap>標記
使用@One或@Many,等價于< association>、< collection>。
首先修改Direction實體類,追加相關(guān)表數(shù)據(jù)存儲的屬性。
public class Direction{
private int id;
private String name;
private List<Subject> subjects;
}
然后定義Mapper,在@Results定義中對subjects屬性描述@Many
@Select({
"select",
"id, name",
"from direction"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
@Result(property="subjects",javaType=List.class,column="id",
many=@Many(select="cn.xdl.ydma.dao.SubjectMapper.selectByDirectionId"))
})
List<Direction> selectAll();
最后在SubjectMapper中定義@Many中select查詢方法
@Select({
"select",
"id, name, direction_id",
"from subject",
"where direction_id = #{direction_id,jdbcType=INTEGER}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
@Result(column="direction_id", property="directionId", jdbcType=JdbcType.INTEGER)
})
List<Subject> selectByDirectionId(Integer direction_id);