当前位置:   article > 正文

数据连表表查询的几种方式_querywrapper连表查询

querywrapper连表查询

一、Mybatius左连接一对一查询

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.bigmi.article.mapper.ArticleMapper">
  4. <resultMap id="resultMap" type="com.bigmi.model.article.pojo.ApArticle">
  5. <--数据库字段与实体类对应关系-->
  6. <id column="id" property="id"/>
  7. <result column="title" property="title"/>
  8. <result column="author_id" property="authorId"/>
  9. <result column="author_name" property="authorName"/>
  10. <result column="channel_id" property="channelId"/>
  11. <result column="channel_name" property="channelName"/>
  12. <result column="layout" property="layout"/>
  13. <result column="flag" property="flag"/>
  14. <result column="images" property="images"/>
  15. <result column="labels" property="labels"/>
  16. <result column="likes" property="likes"/>
  17. <result column="collection" property="collection"/>
  18. <result column="comment" property="comment"/>
  19. <result column="views" property="views"/>
  20. <result column="province_id" property="provinceId"/>
  21. <result column="city_id" property="cityId"/>
  22. <result column="county_id" property="countyId"/>
  23. <result column="created_time" property="createdTime"/>
  24. <result column="publish_time" property="publishTime"/>
  25. <result column="sync_status" property="syncStatus"/>
  26. <result column="static_url" property="staticUrl"/>
  27. </resultMap>
  28. <--id方法名 resultMap数据库字段与实体类映射关系-->
  29. <select id="articleList" resultMap="resultMap">
  30. SELECT
  31. aa.*
  32. FROM
  33. `ap_article` aa
  34. LEFT JOIN ap_article_config aac ON aa.id = aac.article_id
  35. <where>
  36. and aac.is_delete != 1
  37. and aac.is_down != 1
  38. <!-- loadmore -->
  39. <if test="type != null and type == 1">
  40. and aa.publish_time <![CDATA[<]]> #{dto.minBehotTime}
  41. </if>
  42. <if test="type != null and type == 2">
  43. and aa.publish_time <![CDATA[>]]> #{dto.maxBehotTime}
  44. </if>
  45. <if test="dto.tag != '__all__'">
  46. and aa.channel_id = #{dto.tag}
  47. </if>
  48. </where>
  49. order by aa.publish_time desc
  50. limit #{dto.size}
  51. </select>

二、级联查询(注解开发)一对一查询和一对多

  1. @Select("select * from construction_project.subitem where pid = #{pid} and status = 1")
  2. List<Subitem> findSubitemsByPid(String pid);
  3. @Results(id = "subMap",value = {
  4. <--数据库与实体类对应字段-->
  5. @Result(column = "suid",property = "suid"),
  6. @Result(column = "sname",property = "sname"),
  7. @Result(column = "starttime",property = "starttime"),
  8. @Result(column = "endtime",property = "endtime"),
  9. @Result(column = "pid",property = "pid"),
  10. @Result(column = "updatetime",property = "updatetime"),
  11. @Result(column = "status",property = "status"),
  12. <--一对一查询 project是一对一对应的实体类 在suid在的实体类中创建属性 property为实体类中对应的属性名-->
  13. @Result(column = "pid",property = "project",javaType = Project.class,one =
  14. <--对一对一需要的条件路径,在相应的mapper中创建条件-->
  15. @One(select = "com.ioc.mapper.ProjectMapper.findProjectByPid",fetchType = FetchType.EAGER)),
  16. <--一对多查询suid是当前实体类id,需要在当前实体类中创建出一个list集合 property为实体类中对应的list集合名-->
  17. @Result(column = "suid",property = "items",many =
  18. @Many(select = "com.ioc.mapper.ItemMapper.findItemsBySuid",fetchType = FetchType.EAGER)),
  19. })
  20. <--查询对应的sql条件语句-->
  21. @Select("<script> select * from construction_project.subitem " +
  22. "<where> status = 1 " +
  23. "<if test=\"queryString != null and queryString != ''\">" +
  24. "and sname like concat('%',#{queryString},'%')" +
  25. "or suid = #{queryString}"+
  26. "</if>" +
  27. "</where>" +
  28. " limit #{currentPage},#{pageSize}"+
  29. "</script>")
  30. List<Subitem> findAllSubitems(@Param("currentPage") int currentPage,@Param("pageSize") int pageSize,@Param("queryString") String queryString);
  1. public class Subitem {
  2. //数据库中对应字段
  3. private String suid;
  4. private String sname;
  5. private Date starttime;
  6. private Date endtime;
  7. private long pid;
  8. private Date updatetime;
  9. private long status;
  10. //一对一用到的对应实体类字段
  11. private Project project;
  12. //一对多需要的集合,集合中存放需要对应的数据,泛型为实体类
  13. private List<Item> items;
  14. }
  1. 一对一查询对应子表条件
  2. com.ioc.mapper.ProjectMapper.findProjectByPid
  3. @Select("select * from construction_project.project where pid =#{pid} and status=1")
  4. Project findProjectByPid(int pid);
  1. 一对多查询对应子表条件
  2. com.ioc.mapper.ItemMapper.findItemsBySuid
  3. @Select("select * from construction_project.item where suid = #{suid} and status = 1")
  4. List<Item> findItemsBySuid(String suid);

三、MyBatisPlus一对一查询

  1. Page<Dish> pageInfo=new Page<>(page,pageSize);
  2. Page<DishDto> dishDtoPage=new Page<>(page,pageSize);
  3. //条件构造器
  4. LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
  5. queryWrapper.like( name!=null,Dish::getName,name );
  6. //添加排序条件(根据更新时间降序排列)
  7. queryWrapper.orderByDesc( Dish::getUpdateTime );
  8. //执行查询
  9. dishService.page( pageInfo,queryWrapper );
  10. //对象拷贝(忽略record)
  11. BeanUtils.copyProperties( pageInfo,dishDtoPage,"records" );
  12. List<Dish> records = pageInfo.getRecords();
  13. //record,页面是上的所有数据,也就需要展现给用户的数据,获取到record,遍历record获取其中的categoryId
  14. List<DishDto> list= records.stream().map( (item)->{
  15. //DishDto就是需要返回给前端的数据,进行下方对数据的处理
  16. DishDto dishDto=new DishDto();
  17. //将item拷贝到dishDto中
  18. BeanUtils.copyProperties( item,dishDto );
  19. Long categoryId = item.getCategoryId();//分类id
  20. //根据id查询分类对象
  21. Category category = categoryService.getById( categoryId );
  22. if ( category!=null ){
  23. //获取分类名称
  24. String categoryName = category.getName();
  25. //获取出的分类名称赋值给dishDto
  26. dishDto.setCategoryName( categoryName );
  27. }
  28. return dishDto;
  29. } ).collect( Collectors.toList() );
  30. dishDtoPage.setRecords( list );
  31. return R.success( dishDtoPage );
  32. }
  1. if (newsAuthDto ==null){
  2. return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
  3. }
  4. //分页查询
  5. IPage page =new Page(newsAuthDto.getPage(),newsAuthDto.getSize());
  6. Page<NewsNameDto> p = new Page();
  7. LambdaQueryWrapper<WmNews> queryWrapper =new LambdaQueryWrapper<>();
  8. //模糊查询
  9. if (StringUtils.isNotBlank(newsAuthDto.getTitle())){
  10. queryWrapper.like(WmNews::getTitle,newsAuthDto.getTitle());
  11. }
  12. //条件查询全部
  13. if (newsAuthDto.getStatus() != null){
  14. queryWrapper.eq(WmNews::getStatus,newsAuthDto.getStatus());
  15. }
  16. queryWrapper.orderByDesc(WmNews::getSubmitedTime);
  17. //查询作者
  18. page =page(page,queryWrapper);
  19. BeanUtils.copyProperties(page,p,"records");
  20. List<WmNews> pageRecords = page.getRecords();
  21. //NewsNameDto需要将作者姓名和其他信息一起返回给前端,NewsNameDto前端需要的数据
  22. List<NewsNameDto> newsNameDtoList = pageRecords.stream().map((item) ->{
  23. NewsNameDto newsNameDto = new NewsNameDto();
  24. //将数据库实体类WmNews复制到前端需要的数据类中
  25. BeanUtils.copyProperties(item,newsNameDto,"userId");
  26. //查寻需要的数据,进行处理
  27. WmUser wmUser = wmUserMapper.selectById(item.getUserId());
  28. newsNameDto.setAuthorName(wmUser.getName());
  29. return newsNameDto;
  30. }).collect(Collectors.toList());
  31. PageResponseResult responseResult = new PageResponseResult(newsAuthDto.getPage(), newsAuthDto.getSize(), (int) page.getTotal());
  32. responseResult.setData(newsNameDtoList);
  33. return responseResult;
  34. }

四、MyBatisPlus一对多查询


  1. 对需要进行子表的数据封装至list集合中,泛型为实体类
  2. public class DishDto extends Dish {
  3. //菜品对应的口味数据
  4. private List<DishFlavor> flavors = new ArrayList<>();
  5. private String categoryName;
  6. private Integer copies;
  7. }
  1. if(dishDtoList != null){
  2. //如果存在,直接返回,无需查询数据库
  3. return R.success(dishDtoList);
  4. }
  5. //构造查询条件
  6. LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
  7. queryWrapper.eq( dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId() );
  8. queryWrapper.eq( Dish::getStatus,1 );
  9. //添加排序条件
  10. queryWrapper.orderByAsc( Dish::getSort ).orderByDesc( Dish::getUpdateTime );
  11. List<Dish> list = dishService.list( queryWrapper );
  12. dishDtoList= list.stream().map( (item)->{
  13. //给前端返回dishDto中信息
  14. DishDto dishDto=new DishDto();
  15. BeanUtils.copyProperties( item,dishDto );
  16. //获取分类id
  17. Long categoryId = item.getCategoryId();
  18. //查询相应的分类
  19. Category category = categoryService.getById( categoryId );
  20. if ( category!=null ){
  21. String categoryName = category.getName();
  22. dishDto.setCategoryName( categoryName );
  23. }
  24. Long dishId = item.getId();
  25. LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
  26. //更具餐品id获取到口味
  27. wrapper.eq( DishFlavor::getDishId,dishId );
  28. //将查到的数据存入实体类集合中
  29. List<DishFlavor> dishFlavors = dishFlavorService.list( wrapper );
  30. dishDto.setFlavors( dishFlavors );
  31. return dishDto;
  32. } ).collect( Collectors.toList() );
  33. return R.success( dishDtoList );
  34. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/189042
推荐阅读
相关标签
  

闽ICP备14008679号