栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis&MySQL 实现多表联查

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis&MySQL 实现多表联查

需求分析,现有三个表:
user表,存储用户信息,包含用户id,姓名,手机号


product表,存储产品的信息,包含产品的id,产品名,产品的分类目录

transaction表,是一张中间表,存储user表的id、以及product表的id

【一对一查询】
需求:根据用户的id查询用户信息

  1. 在UserMappper.java中声明一个方法,用于查找信息时调用
    //根据用户的id进行查找,查找的内容是多个对象,所以用集合进行封装
    List selectByPrimaryKey(Long id);
  1. 在对应的UserMapper.xml中写SQL语句

        select transaction.userId,transaction.productId,product.ProductName,product.Catalog
        from transaction,product
        where transaction.productId = product.id and transaction.userId = #{userid}
    

注:这里需要特别说明,新创建的resultMap需要和对应的SQL语句连在一起,中间不能出现其他代码

  1. 在ProductTest.java中写测试方法
    首先先把以下内容写在测试是方法前
package com.jyc;

public class TransactionTest {
    SqlSession sqlSession;
    ProductMapper mapper;

    @Before
    public void before() throws Exception{
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession(true);
        //因为我的方法声明在了ProductMapper.class中,所以扫包是扫描这个类
        mapper = sqlSession.getMapper(ProductMapper.class);
    }

    @After
    public void after(){
        sqlSession.close();
    }

}

测试方法

    @Test
    public void findUserProductByUserId(){
    	//传入要查找的用户id,封装在list集合中
        List list = mapper.findUserProductByUserId(1);
        System.out.println(list);
    }

需求2 :根据用户id 查找用户购买的商品信息以及用户的信息
注:这里我们就需要用到中间表Transaction,作为中间的条件

  1. 创建UserTransactionProductDTO.java类,用于封装存储查找的内容
package com.jyc.DTO;

import lombok.Data;

@Data
public class UserTransactionProductDTO {

    private Integer userId;//用户的id
    private String userName;//用户名
    private String userTel;//用户电话号
    private Integer productId;//所购买商品id
    private String productName;//所购买的商品名
    private String productCatalog;//所构面的商品对应的目录
}
  1. 在ProductMapper.java中声明查找信息的方法
    List findUserProductAndUserInfoByUserId(int userid);
  1. 根据DTO类,需要新创建一个resultMap来定义【字段】和【属性】的映射关系
    在ProductMapper.xml输入以下内容
 
 		
        
        
        
        
        
        
    
  1. 编写SQL语句

  1. 编写测试方法
@Test
    public void findUserProductAndUserInfoByUserId(){
    //传入需要查找的用户id
        List userProductAndUserInfoByUserId = mapper.findUserProductAndUserInfoByUserId(1);
        System.out.println(userProductAndUserInfoByUserId);
    }

另外说明:我的包结构如下

至此,全部的需求已完成,感谢阅读,存在不足之处,还请指点!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876741.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号