MyBatis one to one 二次查询

本文详细介绍了在MyBatis中使用二次查询实现一对多关系的数据映射方法,通过PersonDao.xml和CardDao.xml两个映射文件展示了如何配置association元素进行关联查询,以及如何通过嵌套select语句获取关联对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接one to one

二次查询的映射文件
PersonDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hsj.dao.PersonDao">


    <select id="getPersons" resultMap="resultMap_Person">
        select * from t_person
    </select>

    <resultMap type="person" id="resultMap_Person">
        <id column="p_id" property="id"/>
        <result column="p_name" property="name"/>
        <!-- 
        column="p_id":二次查询时传递的值对应的字段
         -->
        <association property="card" column="p_id" javaType="card" select="getCardById">

        </association>
    </resultMap>

    <select id="getCardById" parameterType="int" resultMap="resultMap_card">
        select * from t_card where person_id=#{id}
    </select>

    <resultMap type="card" id="resultMap_card">
        <id column="c_id" property="id"/>
        <result column="c_cardno" property="cardNo"/>
        <result column="c_address" property="address"/>
    </resultMap>


    <!-- 根据人的id值查询人对象 -->
    <select id="getPersonById"  parameterType="int" resultMap="resultMap_Person">
        select * from t_person p inner join t_card c on p.p_id=c.person_id and p_id=#{id}
    </select>
</mapper>

CardDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hsj.dao.CardDao">


    <select id="getCards" resultMap="resultMap_Card">
        select * from t_card 
    </select>

    <resultMap type="card" id="resultMap_Card">
        <id column="c_id" property="id"/>
        <result column="c_cardno" property="cardNo"/>
        <result column="c_address" property="address"/>
        <association property="person" column="person_id" javaType="person" select="getPersonById">

        </association>
    </resultMap>

    <select id="getPersonById" parameterType="int" resultMap="resultMap_Person">
        select * from t_person where p_id=#{id}
    </select>

    <resultMap type="person" id="resultMap_Person">
        <id column="p_id" property="id"/>
        <result column="p_name" property="name"/>
    </resultMap>


    <!-- 根据id查询卡对象 -->
    <select id="getCardById" parameterType="int" resultMap="resultMap_Card">
        select * from t_card where c_id=#{id}
    </select>
</mapper>

测试类接one to one

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值