3、定义sql映射文件
(1)首先是一对多关联:
MyBatis中使用collection标签来解决一对一的关联查询,collection标签可用的属性如下:property:指的是集合属性的值ofType:指的是集合中元素的类型column:所对应的外键字段名称select:使用另一个查询封装的结果
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mucfc.model.CustomerMapper">
<!-- 定义数据库字段与实体对象的映射关系 -->
<resultMap type="Customer" id="customerBean">
<id column="customerId" property="customerId"/>
<result column="customerName" property="customerName"/>
<result column="customerTel" property="customerTel"/>
<!-- 一对多的关系 -->
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="tickets" ofType="Ticket">
<id column="ticketId" property="ticketId"/>
<result column="ticketAddress" property="ticketAddress"/>
<result column="ticketPrice" property="ticketPrice"/>
<result column="ticketCId" property="ticketCId"/>
</collection>
</resultMap>
<!-- 根据id查询Person, 关联将Orders查询出来 -->
<select id="selectCustomerByName" parameterType="string" resultMap="customerBean">
select c.*,t.* from t_customer c,t_ticket t where c.customerId=t.ticketCId and c.customerName =#{customerName};
</select>
</mapper>
(2)接着是一对一关联:
MyBatis中使用association标签来解决一对一的关联查询,association标签可用的属性如下:property:对象属性的名称javaType:对象属性的类型column:所对应的外键字段名称select:使用另一个查询封装的结果
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mucfc.model.TicketMapper">
<!-- 定义数据库字段与实体对象的映射关系 -->
<resultMap type="Ticket" id="ticketBean">
<id column="ticketId" property="ticketId" />
<result column="ticketAddress" property="ticketAddress" />
<result column="ticketPrice" property="ticketPrice" />
<result column="ticketCId" property="ticketCId" />
<!-- 一对一的关系 -->
<!-- property: 指的是属性的值, javaType:指的是元素的类型 -->
<association property="customer" javaType="Customer">
<id column="customerId" property="customerId" />
<result column="customerName" property="customerName" />
<result column="customerTel" property="customerTel" />
</association>
</resultMap>
<!-- 根据id查询ticket, 关联将Customer查询出来 -->
<select id="selectTicketById" parameterType="int" resultMap="ticketBean">
select c.*,t.* from t_customer c,t_ticket t where
c.customerId=t.ticketCId and t.ticketId =#{ticketId}
</select>
</mapper>
文章出处:
http://www.2cto.com/database/201505/399017.html