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; }
至此,技术小哥获取到了自己想要的数据。顺利完成了产品经理给的任务。