Mybatis关联映射之association和collection
最近在学习中,遇到一个混淆点,写篇文章记下来。在Mybatis中使用select语句时,会使用association和collection进行映射。两者的区别主要是,association用于一对一,即一个实体类对象是另一个实体类对象的属性;collection用于一对多,例如一个实体类对象里有一个集合作为属性。
举一个实例。
一辆车只有一个车主,而车主可以拥有好几辆车。
汽车实体类:
public class CarBean { private int id; private String type; private int price; private ManBean man;
车主实体类:
public class ManBean { private int id; private String name; private LocalDate birthday; private int carNum; private List<CarBean> carList;
1、根据汽车id查询汽车,同时需要查询该汽车的车主。
<select id="findById" resultMap="carMap"> select * from t_car where pk_carId = #{id}; </select> <resultMap id="carMap" type="CarBean"> <id column="pk_carId" property="id"></id> <result column="c_type" property="type"></result> <result column="c_price" property="price"></result> <result column="m_name" property="man.name"></result> <!--property为关联属性,select表示该属性的值来自哪个语句块查询结果,column表示该语句块传递哪个列的值--> <association property="man" select="findMan" column="fk_manId"></association> </resultMap> <select id="findMan" resultMap="manMap"> select * from t_man where pk_manId = #{id}; </select> <resultMap id="manMap" type="ManBean"> <id property="id" column="pk_manId"></id> <result property="name" column="m_name"></result> <result property="birthday" column="m_birthday"></result> </resultMap>
2、根据车主id查询车主,同时需要查询该车主的所有汽车
①关联语句块
<select id="findById" resultMap="manMap"> select * from t_man where pk_manId = #{id}; </select> <resultMap id="manMap" type="ManBean"> <id column="pk_manId" property="id"></id> <result property="name" column="m_name"></result> <result property="birthday" column="m_birthday"></result> <result property="carNum" column="carNum"></result> <collection property="carList" select="findCar" column="pk_manId"></collection> </resultMap> <select id="findCar" resultMap="carMap"> select * from t_car where fk_manId = #{id}; </select> <resultMap id="carMap" type="CarBean"> <id property="id" column="pk_carId"></id> <result property="type" column="c_type"></result> <result property="price" column="c_price"></result> </resultMap>
②连表查询
<resultMap id="manMap" type="ManBean"> <id column="pk_manId" property="id"></id> <result property="name" column="m_name"></result> <result property="birthday" column="m_birthday"></result> <result property="carNum" column="carNum"></result> <!--对集合进行映射,ofType指定集合中存放元素的类型--> <collection property="carList" ofType="CarBean"> <id property="id" column="pk_carId"></id> <result property="type" column="c_type"></result> <result property="price" column="c_price"></result> </collection> </resultMap> <select id="findById" resultMap="manMap"> SELECT * FROM t_man m LEFT JOIN t_car c ON m.`pk_manId` = c.`fk_manId` WHERE m.`pk_manId` = #{id}; </select>