Mybatis使用连表查询的操作代码

某天,产品经理给了这么一个需求技术小哥,能不能帮用户添加一个搜索栏,查询包含某个关键字的所有类目。技术小哥稍微想了一下,目前跟类目相关的表有两个,一个是content_category类目表,一个是content_system内容系统表。而用户要查找的关键字是存在content_system表里面,这样一来需要连表查询一下。难度好像不大,也就爽快地答应了。

技术小哥再仔细分析了一下两个表的结构:

CREATE TABLE `content_category` (
  `category_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '类目编号Id',
  `pid` int(10) unsigned DEFAULT NULL COMMENT '上级编号id',
  `level` tinyint(4) NOT NULL COMMENT '层级',
  `name` varchar(20) NOT NULL COMMENT '名称',
  `description` varchar(200) DEFAULT NULL COMMENT '描述',
  `icon` varchar(50) DEFAULT NULL COMMENT '图标',
  `type` tinyint(3) NOT NULL DEFAULT '1' COMMENT '类型(1:普通,2:热门...)',
  `alias` varchar(20) DEFAULT NULL COMMENT '别名',
  `system_id` int(11) DEFAULT NULL COMMENT '系统编号id',
  `ctime` bigint(20) unsigned NOT NULL COMMENT '创建时间',
  `orders` bigint(255) unsigned NOT NULL COMMENT '排序',
  `attention` bigint(20) unsigned NOT NULL COMMENT '关注度',
  PRIMARY KEY (`category_id`),
  KEY `content_category_orders` (`orders`),
  KEY `content_category_pid` (`pid`),
  KEY `content_category_alias` (`alias`),
  KEY `content_category_level` (`level`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='内容类目表';

CREATE TABLE `content_system` (
  `system_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '系统编号id',
  `name` varchar(20) NOT NULL COMMENT '系统名称',
  `code` varchar(20) DEFAULT NULL COMMENT '别名',
  `description` varchar(300) DEFAULT NULL COMMENT '描述',
  `ctime` bigint(20) DEFAULT NULL COMMENT '创建时间',
  `orders` bigint(20) DEFAULT NULL COMMENT '排序',
  PRIMARY KEY (`system_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='内容系统表';

不难看出,两个表都有system_id作为关联,当用户输入一个关键字,例如 code = "news" 时候,系统需要自动搜索出 system_id = 1 的所有类目信息。

于是技术小哥开始了他的工作,首先是定义Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thomson.content.rpc.mapper.ContentCategoryExtMapper">
    <!-- 定义基础类型 -->
    <resultMap id="BaseResultMap" type="com.thomson.content.dao.model.ContentCategory">
        <!-- 实体类的字段名和数据表的字段名映射 -->
        <id column="category_id" jdbcType="INTEGER" property="categoryId" />
        <result column="pid" jdbcType="INTEGER" property="pid" />
        <result column="level" jdbcType="TINYINT" property="level" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="description" jdbcType="VARCHAR" property="description" />
        <result column="icon" jdbcType="VARCHAR" property="icon" />
        <result column="type" jdbcType="TINYINT" property="type" />
        <result column="alias" jdbcType="VARCHAR" property="alias" />
        <result column="system_id" jdbcType="INTEGER" property="systemId" />
        <result column="ctime" jdbcType="BIGINT" property="ctime" />
        <result column="orders" jdbcType="BIGINT" property="orders" />
        <result column="attention" jdbcType="BIGINT" property="attention" />
    </resultMap>
    <!--继承基础类型BaseResultMap, association 一对一关联查询 -->
    <resultMap extends="BaseResultMap" id="ClassesResultMap" type="com.thomson.content.dao.model.ContentCategory">
    </resultMap>      <!-- 这一步是关键的连表查询 -->
    <select id="selectContentCategoryByCode" parameterType="map" resultMap="ClassesResultMap">
        select content_c.* from content_category content_c left join content_system content_s on content_s.code=content_s.code=#{code,jdbcType=VARCHAR}
         where content_s.system_id=content_c.system_id
    </select>
    <!-- 缓存 -->
    <cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
</mapper>

然后是Mapper接口

package com.thomson.content.rpc.mapper;

import com.thomson.content.dao.model.ContentCategory;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 类目ExtMapper
 * Created by Thomson on 2022/01/10.
 * 根据content_system 的 code 获取类目
 */
public interface ContentCategoryExtMapper {
    int up(String code);
    int down(String code);
    List<ContentCategory> selectContentCategoryByCode(@Param("code") String code);
}

接下来是实现类

import com.thomson.Content.dao.model.ContentArticle;
import com.thomson.Content.rpc.mapper.ContentCategoryExtMapper;
import com.thomson.common.annotation.BaseService;
import com.thomson.common.base.BaseServiceImpl;
import com.thomson.Content.dao.mapper.ContentCategoryMapper;
import com.thomson.Content.dao.model.ContentCategory;
import com.thomson.Content.dao.model.ContentCategoryExample;
import com.thomson.Content.rpc.api.ContentCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* ContentCategoryService实现
* Created by Thomson on 2021/01/10.
*/
@Service
@Transactional
@BaseService
public class ContentCategoryServiceImpl extends BaseServiceImpl<ContentCategoryMapper, ContentCategory, ContentCategoryExample> implements ContentCategoryService  {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContentCategoryServiceImpl.class);

    @Autowired
    ContentCategoryExtMapper ContentCategoryExtMapper;

    // @Override
    public List<ContentCategory> selectContentCategoryByCode(String code) {
        return ContentCategoryExtMapper.selectContentCategoryByCode(code);
    }

}

在controll下获取数据

@ApiOperation(value = "类目列表")
    @RequiresPermissions("content:category:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order) {
     Map<String, Object> result = new HashMap<>(2);
        String code = "news";
        List<ContentCategory> categories = ContentCategoryService.selectContentCategoryByCode(code);
        System.out.print("\n"+categories+"\n");
      result.put("rows", categories);     result.put("total", total);
return result;
    }

至此,技术小哥获取到了自己想要的数据。顺利完成了产品经理给的任务。

到此这篇关于Mybatis如何使用连表查询的文章就介绍到这了,更多相关Mybatis连表查询内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • MyBatis-Plus实现连表查询的方法实例

    目录 使用方法 安装 使用 核心类 MPJLambdaWrapper和MPJQueryWrapper MPJLambdaWrapper用法 MPJQueryWrapper 总结 mybatis-plus-join gitee github 使用方法 安装 在项目中添加依赖 <dependency> <groupId>com.github.yulichang</groupId> <artifactId>mybatis-plus-join</artifac

  • mybatisplus如何在xml的连表查询中使用queryWrapper

    目录 在xml的连表查询使用queryWrapper 在mapper接口中定义方法 在mapper xml中 调用该方法 mapper.xml 配合queryWrapper写法 mapper中的接口这么写 xml中${ew.customSqlSegment} 在xml的连表查询使用queryWrapper 在mapper接口中定义方法 List<Map<String,Object>> linkUserAndDept(@Param("ew1") Wrapper&l

  • MyBatis-Plus 如何实现连表查询的示例代码

    在项目开发中,难免会遇到连表查询的操作. 项目中用的是 MyBatis-Plus,是新使用的框架.官方文档看这里. 我写过一篇通过单元测试来验证 MyBatis-Plus 的 CRUD 操作.点这里跳转 今天遇到连表查询的问题,特此记录一下. 遇到需要连表操作,想起 MyBatis 的操作连表查询,要是 MyBatis-Plus 也像 MyBatis 一样,就脑壳痛了.(MyBatis-Plus 是 MyBatis 的增强版) 脑壳痛归脑壳痛,先动手干. 首先 因为官方的内置接口方法都是针对单表

  • Mybatis使用连表查询的操作代码

    某天,产品经理给了这么一个需求技术小哥,能不能帮用户添加一个搜索栏,查询包含某个关键字的所有类目.技术小哥稍微想了一下,目前跟类目相关的表有两个,一个是content_category类目表,一个是content_system内容系统表.而用户要查找的关键字是存在content_system表里面,这样一来需要连表查询一下.难度好像不大,也就爽快地答应了. 技术小哥再仔细分析了一下两个表的结构: CREATE TABLE `content_category` ( `category_id` in

  • MyBatis学习教程(二)—如何使用MyBatis对users表执行CRUD操作

    上一篇文章MyBatis入门学习教程(一)-MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对users表执行CRUD操作.在没奔主题之前,先给大家补充点有关mybatis和crud的基本知识. 什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索.MyBa

  • springboot整合mybatis实现多表查询的实战记录

    目录 什么是mybatis 1.一对一查询(例一个用户一个账户) 1.1.实体类 1.2.数据库表 1.3.持久层接口 2.一对多查询(例一个用户对应多个账户) 2.1.实体类 2.2.数据库表 2.3.持久层接口 3.总结 4.多对多的查询(例一个用户多个角色) 4.1.实体类 4.2.数据库表 4.3.持久层接口 5.多对一(一个用户对应多个老师) 5.1 实体类 5.2.数据库表 5.3.持久层接口 总结 什么是mybatis (1)Mybatis 是一个半 ORM(对象关系映射)框架,它

  • MySQL单表查询常见操作实例总结

    本文实例总结了MySQL单表查询常见操作.分享给大家供大家参考,具体如下: 创建fruits表: CREATE TABLE fruits ( f_id char(10) NOT NULL, s_id INT NOT NULL, f_name char(255) NOT NULL, f_price decimal(8,2) NOT NULL, PRIMARY KEY(f_id) ) ; INSERT INTO fruits (f_id, s_id, f_name, f_price) VALUES(

  • mybatis如何根据表逆向自动化生成代码实例

    前言 自动生成代码总结(1)--(mybatis自动生成实体类.mapper文件.mapper.xml文件) 若采用mybatis框架,数据库新建表,手动编写的话,需要编写大量的实体类.mapper文件.mapper.xml文件,都是一些重复且有规律的工作. 我们可以引用插件,然后做配置,自动生成这些文件,提供工作效率. 本博客包含的内容: ①自动生成插件的引入 ②定义配置文件 ③运行插件,生成代码 1.引入插件 在项目的pom文件中引入generator插件 <plugin> <gro

  • Mybatis实现联表查询并且分页功能

    今天同学突然问我这个怎么搞. 然后自己搞了一下发现这个玩意有坑..就记录一下 0. 表结构 person表 cat表 一个person有多个cat 实体类就这么写 1. 实体类 Person实体类 @Data public class Person implements Serializable { private static final long serialVersionUID = -70682701290685641L; private Integer personid; private

  • asp 获取access系统表,查询等操作代码

    方法一:直接用ado的OpenSchema()方法打开adSchemaTables,建立一个schema记录集 Code: <% Const adSchemaTables = 20 adSchemaColumns = 4 dim Conn,db dim ConnStr db="temp.mdb"       'ACCESS数据库的文件名,请使用相对于网站根目录的的绝对路径 ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data 

  • Java工程mybatis实现多表查询过程详解

    1.先做一些准备工作 我们首先在创建一个 java 工程,还需要创建两张表,它们分别是用户表 user,和帖子表 post,一个户用户可以有多个帖子. user表的结构和数据: -- ---------------------------- -- Table structure for `user` -- ---------------------------- CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT

  • MyBatis实现多表联查的详细代码

    目录 一.通过映射配置文件实现多表联查 二.使用注解的方式 一.通过映射配置文件实现多表联查 首先,使用Mysql数据库,创建两个表,分别为学生表Student表和班级表Class表,在Student表中添加列classid参照主表的列id的外键约束. 学生表Student表: 班级表Class表 : 现在去写Dao层和实体类 Student实体类: package com.ape.bean; import java.util.Date; public class Student { priva

随机推荐