mybatis的使用技巧5——mybatis如何实现一对一功能查询及其对应标签javaType和ofType用法和区别说明

10 篇文章 0 订阅
10 篇文章 0 订阅

在实际项目开发过程中,一对一的关系大量存在,如果无法使用连接查询来获取关联数据,可以使用一对一的查询方法,基本写法与处理一对多的思路类似。

如何查询一对多或者树形结构的问题,具体可参考如下方案步骤,可与一对一参照学习:

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 /> 元素内使用,指明集合中应该包含哪种类型的元素。
  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值