实体类
public class User {
/**
* id
*/
private Integer userId;
/**
* 用户名
*/
private String userName;
/**
* card属性
*/
private Card card;
/**
* 一个用户里面有多个订单
*/
private List<Order> orders = new ArrayList<>();
}
public class Card {
/**
* id
*/
private Integer cardId;
/**
* 编号
*/
private String cardNum;
}
public class Order {
/**
* id
*/
private Integer orderId;
/**
* 商品名称
*/
private String productName;
}
UserDao
/**
* 根据用户id查询用户和他的身份证和他的订单
*/
User getUserAndCardAndOrdersById(Integer userId);
UserMapper
<mapper namespace="com.qianfeng.dao.UserDao">
<!--
resultMap:可以对查询的结果进行解析(表字段跟实体类属性一一对应)
-->
<resultMap id="userMap" type="User">
<!--
column:表中的字段名
property:实体类的属性
-->
<id column="user_id" property="userId"></id>
<!--
id用id,普通字段用result
-->
<result column="user_name" property="userName"></result>
<!--
association:一对一关联使用的标签
property:User类的card属性
column:两表级联的外键
javaType:前面card属性的类型(包名+类名)
-->
<association property="card" column="card_id_fk" javaType="Card">
<id property="cardId" column="card_id"></id>
<result property="cardNum" column="card_num"></result>
</association>
<!--
collection:一对多关系
property:User类中的订单集合属性
column:两表级联的外键
ofType:前面orders集合属性的类型(包名+类名)
-->
<collection property="orders" column="user_id_fk" ofType="Order">
<id column="order_id" property="orderId"></id>
<result column="product_name" property="productName"></result>
</collection>
</resultMap>
<select id="getUserAndCardAndOrdersById" parameterType="java.lang.Integer" resultMap="userMap">
select * from tb_user as u
inner join tb_card as c
on u.card_id_fk=c.card_id
inner join tb_order as o
on u.user_id=o.user_id_fk
where user_id=#{userId}
</select>
</mapper>
多对一就在Order实体类中添加一个User对象 在Order的Mapper中写入
<association property="user" column="user_id_fk" javaType="User">
<id column="order_id" property="orderId"></id>
</association>