配置文件编写总结(三)一对多映射

1.必须的表单和.java文件参见上篇文章:配置文件编写总结(二)一对一映射
2.一对多映射分析
以user为主体查询account,因为一个用户可以有多个账户所以映射关系为一对多。如果表与表的对应关系是一对多,那么则在一个pojo中,添加另外一个pojo的List集合属性。此处就是在user中添加accountList集合,让它作为account的一个属性。以谁为查询主体就配置相应的***.xml文件
在这里插入图片描述

3.在UserDao中添加查询方法:
findUserAccountsByUid()

public interface UserDao {
/**
     * 根据用户的uid,查询到用户的信息,然后查询出该用户的所有账号信息
     * @param uid
     * @return
     */
    User findUserAccountsByUid(int uid);
    }

4.配置userdao.xml文件
使用collection进行一对多的映射,自定义映射规则resultMap id=“userAccountsMap”,在查询中使用resultMap="userAccountsMap"即可调用

<resultMap id="userAccountsMap" type="User">
    <id column="uid" property="uid"/>
    <result column="username" property="username"/>
    <result column="sex" property="sex"/>
    <result column="birthday" property="birthday"/>
    <result column="address" property="address"/>
    <!--使用collection进行一对多的映射
    property="accountList" ofType="Account"
    -->
    <collection property="accountList" ofType="Account">
        <result column="aid" property="aid"/>
        <result column="money" property="money"/>
        <result column="uid" property="uid"/>
    </collection>
</resultMap>
<select id="findUserAccountsByUid" parameterType="int" resultMap="userAccountsMap">
    select * from t_user u,t_account a where a.uid =u.uid and u.uid=#{uid};
</select>


5.Test文件编写

 @Test
    public void testFindUserAccountsByUid() throws IOException {
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user = userDao.findUserAccountsByUid(1);

        System.out.println(user);

        SqlSessionFactoryUtil.closeAndCommit(sqlSession);
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值