Mybatis实现一对多sql collection


MySql实现一对多:??????

创建一个数据库叫mybatis

创建一个room表

create table mybatis.room
(
    id   int         not null
        primary key,
    name varchar(30) not null
);

该表中id为主键

sql中数据

创建一个custom表

create table mybatis.custom
(
    id         int         not null
        primary key,
    name       varchar(30) not null,
    roomnumber int         not null,
    constraint custom_ibfk_1
        foreign key (roomnumber) references mybatis.room (id)
);

create index custom
    on mybatis.custom (roomnumber);

该表中id为主键 roomnumber为外键

sql中数据

 根据room的id获取对应的custom,每个room对应多个custom,每个custom对应一个room。房间和顾客的关系为一对多

查询sql语句

select r.id rid,r.name rname,c.id cid,c.name cname from custom c,room r where r.id=c.roomnumber;

查询结果

Mybatis使用collection语句实现一对多

方法一:连接查询

RoomMapper.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="kite.mapper.RoomMapper">
    <select id="getRoomList" resultMap="RoomCustom">
        select r.id rid,r.name rname,c.id cid,c.name cname from custom c,room r where r.id=c.roomnumber;
    select>
    <resultMap id="RoomCustom" type="Room">
        <result property="id" column="rid"/>
        <result property="name" column="rname"/>
        <collection property="custom" ofType="custom">
            <result property="id" column="cid"/>
            <result property="name" column="cname"/>
        collection>
    resultMap>
mapper>