Mybatis进阶学习笔记——关系查询——一对一查询

时间:2022-10-01 07:17:48

用户和订单的需求

通过查询订单,查询用户,就是一对一查询

(1)自定义JavaBean(常用,推荐使用)

     <select id="queryOrderUser" resultType="OrderUser">
SELECT o.id,o.user_id,u.name,o.productname
FROM t_order o LEFT JOIN t_user u ON o.user_id= u.id
</select>

OrderUser.java:

 package cn.sm1234.domain;

 public class OrderUser extends Order {

     //Order中没有name
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }
     @Test
public void test1() {
SqlSession sqlSession = SessionUtils.getSession();
// getMapper(): 返回指定接口的动态代理的实现类对象
OrderDao dao = sqlSession.getMapper(OrderDao.class);
List<OrderUser> list = dao.queryOrderUser();
for (OrderUser orderUser : list) {
System.out.println(orderUser.getName()+"-"+orderUser.getProductname());
}
sqlSession.commit();
sqlSession.close();
}

OrderDao.java:

 public interface OrderDao {

     /**
* 查询订单,并且关联查询用户信息
*/
public List<OrderUser> queryOrderUser();
}

(2)ResultMap封装

     <!-- type="实体类" -->
<resultMap type="Order" id="OrderUserResultMap">
<id column="id" property="id"/>
<result column="productname" property="productname"/>
<result column="orderno" property="orderno"/>
<!-- user_id封装到User中 -->
<!-- 关联属性
property:关联属性名称(Order类中的user)
javaType:类型(User (即User user))
-->
<association property="user" javaType="User">
<!-- column中的字段名称应该为当前查询结果的字段名称 -->
<id column="user_id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="password"/>
</association> </resultMap> <select id="queryOrderUserResultMap" resultMap="OrderUserResultMap">
SELECT o.id,o.user_id,u.name,o.productname
FROM t_order o LEFT JOIN t_user u ON o.user_id= u.id
</select>

Order.java:

 package cn.sm1234.domain;

 public class Order {

     private Integer id;
private String productname;
private String orderno;
private Integer userId; private User user; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getOrderno() {
return orderno;
}
public void setOrderno(String orderno) {
this.orderno = orderno;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
} }
     /**
* 查询订单,查询用户(ResultMap)
* @return
*/
public List<Order> queryOrderUserResultMap();
     @Test
public void test2() {
SqlSession sqlSession = SessionUtils.getSession();
// getMapper(): 返回指定接口的动态代理的实现类对象
OrderDao dao = sqlSession.getMapper(OrderDao.class);
List<Order> list = dao.queryOrderUserResultMap();
for (Order order : list) {
System.out.println(order.getProductname()+"-"+order.getUser().getName());
}
sqlSession.commit();
sqlSession.close();
}