举个例子:一个学生对应一个地址。
学生表t_student(id,name,age,addressId),addressId是外键,关联地址表t_address(id,sheng,shi,qu)的主键。
如何根据学生表的id,查到学生的全部信息(id,name,age,sheng,shi,qu)呢?关联查询,用MyBatis怎么实现呢?
在Java的实体类Student中引入Address实体。
实体类Student:
属性:id,name,age,address
实体类Address:
属性:id,sheng,shi,qu
第一种方式:
<select id="findWithAddressById" resultMap="StudentResult" parameterType="Integer">
select * from t_student s join t_address a on s.addressId=a.id where s.id=#{id}
</select>
返回一个映射:StudentResult:
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="address.id" column="addressId"/>
<result property="address.sheng" column="sheng"/>
<result property="address.shi" column="shi"/>
<result property="address.qu" column="qu"/>
</resultMap>
右边的column是字段,映射到对应返回参数Student的属性中,通过studentMapper.findWithAddressById获得了这个对象。
第二种方式:
和第一种唯一的区别是:映射的写法不同:
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" javaType="Address">
<result property="id" column="addressId"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</association>
</resultMap>
Student实体中address属性是个Address实体类型,再通过Student字段addressId与Address实体的id对应映射。
第三种方式:
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" resultMap="AddressResult"></association>
</resultMap>
<resultMap type="Address" id="AddressResult">
<id property="id" column="addressId"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</resultMap>
和第二中一样的意思,只不过是把Address单独抽取出来。
第四种方式
这是开发中最常见的方式,复用性比较强。
新建一个AddressMapper接口,和AdderssMapper.xml 单独写。
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" column="addressId" select="com.java.mappers.AddressMapper.findById"></association>
</resultMap>
直接调用Address的接口方法。
public interface AddressMapper {
public Address findById(Integer id);
}
<resultMap type="Address" id="AddressResult">
<result property="id" column="id"/>
<result property="sheng" column="sheng"/>
<result property="shi" column="shi"/>
<result property="qu" column="qu"/>
</resultMap>
<select id="findById" parameterType="Integer" resultType="Address">
select * from t_address where id=#{id}
</select>
这样写,不容易乱,面向对象的思想。这也是以后开发经常会用的方法。