mybatis中的一对多(多表)查询

mybatis中的一对多(多表)查询
如果拿出每一个订单,他都只能属于一个用户。
所以mybatis就把多对一看成一对一
步骤;
1.用户表和账户表:
一个用户可以有多个账户
一个账户只能属于一个用户
2.建立两个实体类:用户实体类和账户实体类
让用户和账户的实体类都能体现出一对多的关系
3.建立两个配置文件
用户配置文件
账户配置文件
4.实现配置
当我们查询用户时,可以同时得到用户下所包含的账户信息
当我们查询账户时,可以得到账户所属用户信息

怎么说呢?
学的sql语句没有卵用,还得在实际情况下面学!!!
你比如说account(账户的ID)有个外键就是(userid)
关联子查询:用很多次

column是代表从哪获取的

一对多关系映射,主表实体应该包含在从表实体的集合引用

private List<Account> accounts;

public List<Account> getAccounts() {
    return accounts;
}

public void setAccounts(List<Account> accounts) {
    this.accounts = accounts;
}

写IuserDao.xml

 <!-- 定义User的resultMap-->
<resultMap id="userAccountMap" type="user">
    <id property="id" column="id"></id>
    <result property="username" column="username"></result>
    <result property="address" column="address"></result>
    <result property="sex" column="sex"></result>
    <result property="birthday" column="birthday"></result>
    <!-- 配置user对象中accounts集合的映射 -->
    <collection property="accounts" ofType="account">
        <id column="aid" property="id"></id>
        <result column="uid" property="uid"></result>
        <result column="money" property="money"></result>
    </collection>
</resultMap>

<!-- 查询所有(修改一下sql语句) -->
<select id="findAll" resultMap="userAccountMap">
    select * from user u left outer join account a on u.id = a.uid
</select>


接下来直接查询,就可以将一个用户下的多个账户都查询出来。

/**
* 测试查询所有
*/
@Test
public void testFindAll(){
List users = userDao.findAll();
for(User user : users){
System.out.println("-----每个用户的信息------");
System.out.println(user);
System.out.println(user.getAccounts());
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值