Mybatis多表联合查询,嵌套查询,动态SQL

Mybatis多表联合查询,嵌套查询,动态SQL

Mybatis多表联合查询

一对一

一对一查询:通过一方关联查询出另外一方的关系数据

  1. 创建数据库和相关数据表
  2. 创建需要关联查询的实体类,里面包含相关的属性
//丈夫查妻子
public class Husband {
       
    private Integer id;    
    private String name;   
    private Wife wife;
}
public class Wife {
   

    private Integer id;
    private String name;
}
  1. 编写HusbandMapper接口,为了调用方法
public interface HusbandMapper {
   

    List<Husband> findByName(String name);
}
  1. 编写相关的Sql语句
    • 关联查询的时候需要用resultMap进行自定义标签的映射
    • 非关联单表查询的时候可以直接使用resultType进行查询
    • property表示属性对应的是实体类的字段名称
    • column表示的是自己定义的属性值,与sql语句定义的字段名称相同
    • associationjavaType在一对一关联查询的时候使用
    • association里映射的是被关联查询的表和属性值
   <resultMap id="husbandAndWife" type="husband">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="wife" javaType="wife">
            <id property="id" column="wid"/>
            <result property="name" column="wname"/>
        </association>
    </resultMap>
    
    <select id="findByName" parameterType="string" resultMap="husbandAndWife">
        select h.id,h.name,w.id wid, w.name wname from t_husband h,t_wife w 
        where h.id = w.id and h.name = #{name}
    </select>
  1. 编写HusbandMapperTest测试类
public class CustomerMapperTest {
   

    private SqlSessionFactory sqlSessionFactory;

   @Before
   public void init() throws IOException {
   
       //加载核心配置文件
       InputStream inputStream = Resources.getResourceAsStream("mybatis-config");
       //创建会话工厂
       sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   }

   @Test
   public void test(){
   
       //打开会话工厂
       SqlSession sqlSession = sqlSessionFactory.openSession();
       //获取内容
       CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
       //遍历Customer表数据
       List<Customer> ret = mapper.findByName("aa");
       //输出
       System.out.println(ret);
   }
一对多

一个用户可以关联查询出自己的订单信息

  1. 创建数据库和相关数据表
  2. 创建需要关联查询的实体类,里面包含相关的属性
public class Customer {
   

    private Integer id;
    private String name;
    
    private List<Order> orders;
}
public class Order {
   

    private Integer id;
    private String goods;
    
  • 8
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值