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連表查詢內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: