MyBatis教程之七注解式多表关系代码详解

在之前的一篇文章中我们使用了xml配置方式实现了多表关系,那么本篇就来说说如何使用注解来实现多表关系
三个表:
购物车
用户表
订单表
关系:
用户与购物车一对一:使用@One或直接用@Result标记
用户和订单一对多:使用@Many或者使用@ResultMap
建表语句:

create table tb_cart(id int auto_increment primary key,money double,count int);

create table tb_user(id int auto_increment primary key,usename varchar(16),password varchar(32),cid int, foreign key(cid) references tb_cart(id));

create table tb_order(id int auto_increment primary key,money double,rname varchar(10),rphone varchar(15),uid int,foreign key(uid) references tb_user(id));

直接看接口:


public interface TbUserMapper {


    @Insert("insert into tb_user(usename,password,cid) values(#{usename},#{password},#{cart.id})")
    @Options(keyProperty="id")
    int save(TbUser user);

    @Select("select * from tb_user")
    @ResultType(TbUser.class)
    List queryAll();
    //嵌套对象:一对一
    //连接查询
    @Select("select u.*,c.* from tb_user u left join tb_cart c on u.cid=c.id")
    @Results({
        @Result(id=true,property="id",column="id"),
        @Result(property="usename" ,column="usename"),
        @Result(property="password" ,column="password"),
        @Result(property="cart.id",column="cid"),
        @Result(property="cart.money",column="money"),
        @Result(property="cart.count",column="count")
    })
    List queryAllByOne1();
    //嵌套查询
    @Select("select * from tb_user")
    @Results({
        @Result(id=true,property="id",column="id"),
        @Result(property="usename" ,column="usename"),
        @Result(property="password" ,column="password"),
        @Result(property="cart",column="cid",
        one=@One(select="org.qf.dao.TbCartMapper.queryById",fetchType=FetchType.EAGER))
    })
    List queryAllByOne2();

    //一对多的实现
    //嵌套查询
    @Select("select * from tb_user")
    @Results({
        @Result(id=true,property="id",column="id"),
        @Result(property="usename" ,column="usename"),
        @Result(property="password" ,column="password"),
        @Result(property="orders",column="id",
        many=@Many(fetchType=FetchType.EAGER,select="org.qf.dao.TbOrderMapper.queryByUid"))
    })
    List queryAllByMany1();

    //连接查询
    @Select("select u.*,o.*,o.id odid from tb_user u left join tb_order o on u.id=o.uid")
    @ResultMap("org.qf.dao.TbUserMapper.rm1")
    List queryAllByMany2();
}

对应的额@ResultMap对应的标签文件



<mapper namespace="cn.code404.dao.TbUserMapper">

    <resultMap type="TbUser" id="rm1">
        <id property="id" column="id">id>
        <result property="usename" column="usename" />
        <result property="password" column="password" />
        <collection property="orders" ofType="TbOrder">
        <id property="id" column="odid"/>
        <result property="money" column="money"/>
        <result property="rname" column="rname"/>
        <result property="rphone" column="rphone"/>
        collection>
    resultMap>
mapper>

你可能感兴趣的:(MyBatis,mybatis,注解多表关系,ResultMap)