Mybatis 注解接口一对多快捷关联查询简单例子@Many@Results@Result

这是Mybtis表之间关联关系为一对多的基于注解的查询例子

1,准备C1,C2类和D1,D2数据库表,配置项目的mybatis配置。

类:

C1:x,xx,C2List

C2:xxxx,xxxxx

2,写C1Mapper.java,C2Mapper.java用与写注解和接口

@Select用于写SQL语句,

@Results用于包含多个@Result,

@Result中column和property指明了类-表的属性和字段的对应

最后一个@Result中的column则是从执行后@Select中SQL选出的字段名

用于做关联接下来要查询的D2表依据

@Many中则指出了接下来要执行的SQL

C1Mapper.java

package com.xxx.dao;

import com.xxx.xxx.C1;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface C1Mapper {
    @Select("select * from D1 where x=#{x}")
    @Results({
            @Result(id = true,column = "x",property = "x"),
            @Result(column = "xx",property = "xx"),
            @Result(column = "x",property = "C2List",
                    many = @Many(select = "com.xxx.dao.C2Mapper.selectC2"))
            })
    Users selectC1(int x);
}

C2Mapper.java

package com.xxx.dao;

import com.xxx.xxx.C2;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface C2Mapper {
    @Select("select * from D2 where xxxx=#{xxxx}")
    List<C2> selectC2(int xxxx);
}

3,配置mybatis配置文件mybatis-config.xml

        <mapper class="com.xxx.dao.C1Mapper"/>
        <mapper class="com.xxx.dao.C2Mapper"/>

4,调用

    @Test
    public void selectC1Test(){
        SqlSession session = MybatisUtils.getSeesion();//自定义的工具类获取session
        C1Mapper mapper = session.getMapper(C1Mapper.class);
        C1 c1 = mapper.selectC1(x);
        System.out.println(c1.toString());
        session.close();

    }

5,调用后的结果应该是

C1{x   ,  xx  ,  C2List= [  c2{}   , c2{}  ]}

即C1中包含大于等于0个C2

 C1{x=x, xx='xx', C2List=[C2{xxxx=xxxx, xxxxx='xxxxx'},C2{xxxx=xxxx, xx='xxxxx'}]}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值