1一对一查询
模型:
User表
Order表
Order实体类:
public class Order_ {
private int id;
private Date ordertime;
private int total;
//订单的拥有者
private User user;
//getter和setter方法略..
}
需求:查询一个订单及订单的拥有者的信息
执行下述语句得到的结果怎么进行映射?
SELECT *, o.id oid FROM user_ u, order_ o WHERE o.uid = u.id
数据库查询结果:
MyBatis配置
OrderMapper.xml
<mapper namespace="com.itheima.mapper.OrderMapper">
<resultMap id="orderAndUser" type="order_">
<id property="id" column="oid"/>
<result property="ordertime" column="ordertime"/>
<result property="total" column="total"/>
<association property="user" javaType="user">
<id property="id" column="uid"/>
<id property="username" column="username"/>
<id property="password" column="password"/>
<id property="birthday" column="birthday"/>
</association>
</resultMap>
<select id="selectWithUser" resultMap="orderAndUser">
SELECT *, o.id oid FROM user_ u, order_ o WHERE o.uid = u.id
</select>
</mapper>
2一对多查询
User实体类:
public class User {
private int id;
private String username;
private String password;
private Date birthday;
private List<Order_> orderList;
}
需求:查询一个用户的信息及其拥有的订单信息
SQL语句:
SELECT *, o.id oid FROM user_ u, order_ o WHERE u.id = o.uid;
查询结果:
分析:一对多与一对一查询的不同在于User实体类中的orderList是一个集合,所以在一对一的基础上掌握集合的配置方法就可以了
MyBatis配置
<mapper namespace="com.itheima.mapper.UserMapper">
<resultMap id="userMap" type="user">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="birthday" property="birthday"/>
<!--配置集合信息
property: 集合名称
ofType:集合中的数据类型
-->
<collection property="orderList" ofType="order_">
<id column="oid" property="id"/>
<id column="ordertime" property="ordertime"/>
<id column="total" property="total"/>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
SELECT *, o.id oid FROM user_ u, order_ o WHERE u.id = o.uid;
</select>
</mapper>
3多对多模型
模型: