在实际项目开发过程中,一对一的关系大量存在,如果无法使用连接查询来获取关联数据,可以使用一对一的查询方法,基本写法与处理一对多的思路类似。
如何查询一对多或者树形结构的问题,具体可参考如下方案步骤,可与一对一参照学习:
mybatis的使用技巧3——查询树形结构,支持一对多和递归查询
1.存在如下定义的数据模型:
@Data
@TableName(value = "person_info")
public class PersonInfo extends BaseEntity<PersonInfo>
{
@TableField(exist = false)
private String staName;
@TableField(exist = false)
private String otherName;
//需要关联查询的数据
@TableField(exist = false)
private PersonApplyDetail detailObj;
@TableField(exist = false)
private BigDecimal maxAge;
@TableField(exist = false)
private BigDecimal minAge;
}
2.mapper对应的数据接口:
List<PersonInfo> getQueryData(PersonInfo info);
3.对应的mybatis-xml文件写法:
<resultMap id="PersonInfoMap"
type="com.test.other.entity.PersonInfo" autoMapping="true" >
<result property="id" column="id" />
<collection column="id" property="detailObj"
javaType="com.test.other.entity.PersonApplyDetail"
select="getPersonApplyDetailByFid" autoMapping="true">
</collection>
</resultMap>
<select id="getPriceContrastData" parameterType="SuppliesInfo"
resultMap="SuppliesPriceContrastMap">
select sdsi.*
from person_info sdsi
left join person_apply_detail sdsad
on sdsi.id = sdsad.supplies_id and sdsad.del_flag = 0
<where>
sdsi.del_info = 0 and sdsad.status = 1
<if test="staId != null "> and sdsi.sta_id = #{staId}</if>
</where>
GROUP BY sdsad.supplies_id
order by sdsi.create_time desc
</select>
<select id="getPersonApplyDetailByFid"
resultType="com.test.other.entity.PersonApplyDetail">
select sdsad.*,sta.sta_name staName
from person_apply_detail sdsad
left join sys_station sta
on sta.dept_id = sdsad.sta_id and sta.del_flag = 0
<where>
sdsad.del_flag = 0 and sdsad.status = 1
<if test="suppliesId != null "> and sdsad.supplies_id = #{id}</if>
</where>
order by sdsad.create_time desc
limit 1
</select>
4.需要特别注意的点:
与一对多相比,其实主要区别在于使用javaType和ofType属性。
在MyBatis中,javaType 和 ofType 都用于指定Java类中属性的类型,但它们适用于不同的场景。
- javaType:用于指定单一对象的Java类型。它通常用在 <association />标签中,告诉MyBatis该如何实例化处理这个单一对象。
- ofType:用于指定集合中元素的Java类型。它在 <collection /> 元素内使用,指明集合中应该包含哪种类型的元素。