mysql+mybatis递归调用
递归调用的应用场景常常出现在多级嵌套的情况,比如树形的菜单。下面通过一个简单的例子来实现mysql+mybatis的递归。
数据模型
private Integer categoryId;
private String categoryName;
private Integer isRoot;
private Integer categoryLevel;
private Integer rootCategoryId;
private Integer parentCategoryId;
private String parentCategoryName;
以上是一个简单的类目的数据实体,主要要注意通过乐parentCategoryId实现了父子的关联。
数据库数据

我们可以很简单的通过父级的id获取其直接子级列表。但是如果我们想要通过某一父级id获取其直接下属和间接下属的(子,孙,曾孙等)列表呢?这就需要用到递归来实现。
实现方法
首先,我们在实体类下面加上这么一个属性。
public List<TCategory>childList=new ArrayList<TCategory>();//子Category列表
然后,我们编写xml文件中的ResultMap,如下。
<!-- 带有chlidList的map -->
<resultMap id="TreeMap" type="com.qgranite.entity.TCategory">
<id column="category_id" property="categoryId" jdbcType="INTEGER" />
<result column="category_name" property="categoryName"
jdbcType="VARCHAR" />
<result column="category_remark" property="categoryRemark"
jdbcType="VARCHAR" />
<result column="category_type" property="categoryType"
jdbcType="INTEGER" />
<result column="is_root" property="isRoot" jdbcType="INTEGER" />
<result column="category_level" property="categoryLevel"
jdbcType="INTEGER" />
<result column="root_category_id" property="rootCategoryId"
jdbcType="INTEGER" />
<result column="parent_category_id" property="parentCategoryId"
jdbcType="INTEGER" />
<result column="parent_category_name" property="parentCategoryName"
jdbcType="VARCHAR" />
<collection property="childList" column="category_id"
ofType="com.qgranite.entity.TCategory" select="selectRecursionByParentCategoryId"></collection>
</resultMap>
最后一句是关键,它说明了递归所需要调用的方法selectRecursionByParentCategoryId。
然后我们来写这个递归方法。
<!-- 根据父键递归查询 -->
<select id="selectRecursionByParentCategoryId" resultMap="TreeMap"
parameterType="java.lang.Integer">
select
*
from t_category
where is_del=0
and
parent_category_id=#{_parameter,jdbcType=INTEGER}
</select>
注意这边的resultMap就是上述定义的resultMap.
如果要递归获取所有的TCategory,我们只要获取所有category_type=1(即根类目),然后从根目录递归下去,注意这边的resultMap必须为TreeMap,才会触发递归。
<!-- 递归查询所有 -->
<select id="selectRecursionAll" resultMap="TreeMap">
select
*
from t_category
where is_del=0
and
category_type=1
</select>
接下来写后台调用方法。
/**
* 根据特定父类递归查询所有子类
*
* @param categoryId
* @return
*/
public List<TCategory> allCategoryRecursion() {
return baseDao
.findTList(
"TCategoryMapper.selectRecursionAll");
}
/**
* 根据特定父类递归查询所有子类
*
* @param categoryId
* @return
*/
public List<TCategory> subCategoryListByParentId(int categoryId) {
return baseDao
.findTListByParam(
"TCategoryMapper.selectRecursionByParentCategoryId",
categoryId);
}
/**
* 根据categoryId获取子孙categoryId的id字符串,用逗号隔开
*
* @param categoryId
* @return
*/
public String subCategoryStrByParentId(Integer categoryId) {
String categoryStr = categoryId.toString();
List<TCategory> categoryList = baseDao
.findTListByParam(
"TCategoryMapper.selectRecursionByParentCategoryId",
categoryId);
int size = categoryList.size();
for (int i = 0; i < size; i++) {
TCategory category = categoryList.get(i);
categoryStr = categoryStr + "," + category.getCategoryId();
if (!category.getChildList().isEmpty()) {
Iterator<TCategory> it = category.getChildList().iterator();
while (it.hasNext()) {
categoryStr = categoryStr + "," + it.next().getCategoryId();
}
}
}
return categoryStr;
}
其中baseDao的代码如下。
package com.qgranite.dao; import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List; import javax.annotation.Resource; import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository; /**
* 所有dao基类
*
* @author xdx
*
* @param <T>
* @param <PK>
*/
@Repository("baseDao")
public class BaseDao<T, PK extends Serializable> {
private Class<T> enetityClass;
@Resource(name = "sqlSessionTemplate")
private SqlSessionTemplate sqlSessionTemplate; // 构造方法,根据实例类自动获取实体类型,这边利用java的反射
public BaseDao() {
this.enetityClass = null;
Class c = getClass();
Type t = c.getGenericSuperclass();
if (t instanceof ParameterizedType) {
ParameterizedType p = (ParameterizedType) t;
Type[] type = p.getActualTypeArguments();
this.enetityClass = (Class<T>) type[0];
}
} /**
* 获取实体
*
* @param id
* @return
*/
public T getT(String sql, Object param) {
return sqlSessionTemplate.selectOne(sql, param);
}
/**
* 不带查询参数的列表
* @param str
* @return
* @throws Exception
*/
public List<T> findTList(String sql){
return sqlSessionTemplate.selectList(sql);
} /**
* 带有参数的列表
*
* @param str
* @param param
* @return
* @throws Exception
*/
public List<T> findTListByParam(String sql, Object param) {
return sqlSessionTemplate.selectList(sql, param);
} /**
* 插入一条数据,参数是t
*
* @param sql
* @param t
* @return
*/
public int addT(String sql, T t) {
return sqlSessionTemplate.insert(sql, t);
}
/**
* 修改一条数据,参数是t
* @param sql
* @param t
* @return
*/
public int updateT(String sql,T t){
return sqlSessionTemplate.update(sql, t);
}
/**
* 删除t,参数是主键
* @param sql
* @param t
* @return
*/
public int deleteT(String sql,PK pk){
return sqlSessionTemplate.delete(sql, pk);
}
/**
* 根据param获取一个对象
* @param sql
* @param param
* @return
*/
public Object getObject(String sql,Object param){
return sqlSessionTemplate.selectOne(sql,param);
}
}
mysql+mybatis递归调用的更多相关文章
- Java Spring+Mysql+Mybatis 实现用户登录注册功能
前言: 最近在学习Java的编程,前辈让我写一个包含数据库和前端的用户登录功能,通过看博客等我先是写了一个最基础的servlet+jsp,再到后来开始用maven进行编程,最终的完成版是一个 Spri ...
- mysql中递归树状结构<转>
在Oracle 中我们知道有一个 Hierarchical Queries 通过CONNECT BY 我们可以方便的查了所有当前节点下的所有子节点.但很遗憾,在MySQL的目前版本中还没有对应的功能. ...
- mysql 树结构递归处理
日常开发中我们经常会遇到树形结构数据处理,一般表结构通常会常用id,pid这种设计方案. 之前用oracle.sqlServer数据库,用相应的语法即可获取树形结构数据(oracel:connect ...
- springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+freemarker+layui
前言: 开发环境:IDEA+jdk1.8+windows10 目标:使用springboot整合druid数据源+mysql+mybatis+通用mapper插件+pagehelper插件+mybat ...
- springboot学习笔记:10.springboot+atomikos+mysql+mybatis+druid+分布式事务
前言 上一篇文章我们整合了springboot+druid+mybatis+mysql+多数据源: 本篇文章大家主要跟随你们涛兄在上一届基础上配置一下多数据源情况下的分布式事务: 首先,到底啥是分布式 ...
- Python-函数的递归调用
递归调用顾名思义即在函数内部调用函数(自己调用自己),通常用它来计算阶乘,累加等 注意: - 必须有最后的默认结果 if n ==0,(不能一直调用自己,如果没有可能会造成死循环) - 递归参数必 ...
- mybatis动态调用表名和字段名
以后慢慢启用个人博客:http://www.yuanrengu.com/index.php/mybatis1021.html 一直在使用Mybatis这个ORM框架,都是使用mybatis里的一些常用 ...
- 关于C++的递归调用(n的阶乘为例)
C++,是入门编程界的一门初期的语言.今天我们浅谈一下有关C++的递归调用. 在没有继承,多态,封装之前,C++几乎看成是C语言,除了一些简单的输出和头文件. 具体代码实现如下: #include&l ...
- java中父类与子类, 不同的两个类中的因为构造函数由于递归调用导致栈溢出问题
/* 对于类中对成员变量的初始化和代码块中的代码全部都挪到了构造函数中, 并且是按照java源文件的初始化顺序依次对成员变量进行初始化的,而原构造函数中的代码则移到了构造函数的最后执行 */ impo ...
随机推荐
- spring boot跨域设置
定义 跨域是指从一个域名的网页去请求另一个域名的资源 跨域背景 限制原因 如果一个网页可以随意地访问另外一个网站的资源,那么就有可能在客户完全不知情的情况下出现安全问题 为什么要跨域 公司内部有多个不 ...
- Java多线程由易到难
线程可以驱动任务,因此你需要一种描述任务的方式,这可以由Runnable接口来提供.要想定义任务,只需实现Runnable接口并编写run方法,使得该任务可以执行你的命令. public class ...
- div内长串数字或字母不断行处理
比如: <div>1111tryrt645645rt4554111112324353453454364</div> <div>qwewretrytuytuiyiuo ...
- bash, sh, dash 傻傻分不清楚
原文链接,转载请注明出处: http://www.happycxz.com/m/?p=137 常见shell类型 Bourne shell (sh) UNIX 最初使用,且在每种 UNIX 上都可以使 ...
- MySQL子查询优化实例
优化:子查询改写成关联查询 线上遇到问题,查询较慢,如为对应SQL的查询执行计划: localhost.\G . row *************************** id: select_ ...
- netty 入门(一)
netty Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序.更确切的讲是一个组件,没有那么复杂. 例子 一 Discard服务器端 我们 ...
- OpenCV探索之路(二十七):皮肤检测技术
好久没写博客了,因为最近都忙着赶项目和打比赛==| 好吧,今天我打算写一篇关于使用opencv做皮肤检测的技术总结.那首先列一些现在主流的皮肤检测的方法都有哪些: RGB color space Yc ...
- Python环境变量搭建
1.首先下载相对应的Python版本,安装后在系统环境变量的path路径下加入安装的默认路径: 2.测试:dos命令下输入python.回车,然后测试,exit()退出来,测试完成.
- 书写规范的javaScript
书写可维护的代码 代码的维护,修改以及扩展都是需要时间和人力成本的,所以为了减少浪费不必要的成本,从一开始就要书写可维护的代码,这样给自己也给项目其他人提供便利. 书写可维护的代码意味着你的代码是: ...
- webpack 3.X学习之Babel配置
Babel是什么 Babel是一个编译JavaScript的平台,它的强大之处表现在可以通过编译帮你达到: 使用下一代的javascript(ES6,ES7,--)代码,即使当前浏览器没有完成支持: ...