【mybatis】一对一查询----resultType &resultMap

xiaoxiao2025-05-16  32

resultType实现一对一查询

需求:查询订单信息,关联查询创建订单的用户信息

分析:订单表是主查询表,用户表是关联表

使用内连接还是外连接?

由于orders表中有user_id这个外键,外键关联查询用户只能查询出一条记录,可以使用内连接。

SELECT orders.*, user.username, user.sex, user.address FROM orders, USER WHERE orders.user_id=user.id

写过sql语句,就需要根据查询对象创建pojo

1、创建pojo对象

将sql查询的结果映射到pojo中,这个pojo包括所有的查询列名。如果已有的pojo类不能包含所有的对象,那就需要创建一个新的pojo。

创建pojo继承包含查询字段较多的pojo类。

2、定义mapper.xml中的statement

<mapper namespace="com.mybatis.mapper.OrdersMapperCustomer"> <select id="findOrdersUser" resultType="com.mybatis.pojo.OrderCustomer"> SELECT orders.*, user.username, user.sex, user.address FROM orders, USER WHERE orders.user_id=user.id </select> </mapper>

resultType输出类型是刚刚创建的pojo

3、写接口

public List<OrderCustomer> findOrdersUser() throws Exception;

resultMap实现一对一查询

需求:

将查询结果中的订单信息映射到Orders对象中。

我们在Orders类中添加了User信息,将查询结果的User信息映射到Orders对象中的User对象中。

1、定义resultMap

<resultMap type="com.mybatis.pojo.Orders" id="OrderMessage"> <id column="id" property="id"/> <result column="user_id" property="userId"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/> <association property="user" javaType="com.mybatis.pojo.User"> <id column="user_id" property="id"/> <result column="username" property="username"/> <result column="sex" property="sex"/> <result column="address" property="address"/> </association> </resultMap>

type 因为查询结果中的Orders信息要映射到Orders表 故Type填Orders

<id> Orders的唯一标识

关联表使用<association> , 将查询结果的User信息映射到User对象中

<id>  column :Orders表中的user_id外键也就是user表的主键, property : user对象的id

2、定义接口

public List<Orders> findOrdersUser() throws Exception;

返回值类型是对应resultMap中的type,也就是映射到主表对应的对象

3、测试

小结

实现一对一查询:

resultType:使用resultType实现较为简单,如果pojo中没有包括查询出来的列名,需要增加列名对应的属性,即可完成映射。

如果没有查询结果的特殊要求建议使用resultType。

resultMap:需要单独定义resultMap,实现有点麻烦,如果对查询结果有特殊的要求,使用resultMap可以完成将关联查询映射pojo的属性中。

resultMap可以实现延迟加载,resultType无法实现延迟加载。

 

转载请注明原文地址: https://www.6miu.com/read-5030196.html

最新回复(0)