添加online模块

This commit is contained in:
D 2024-01-27 00:51:40 +08:00
parent dea2cc9df2
commit 7629aab6e4
15 changed files with 1243 additions and 27 deletions

18
pom.xml
View File

@ -24,7 +24,7 @@
<kaptcha.version>2.3.3</kaptcha.version>
<pagehelper.boot.version>1.4.7</pagehelper.boot.version>
<fastjson.version>2.0.45</fastjson.version>
<oshi.version>6.4.10</oshi.version>
<oshi.version>6.4.11</oshi.version>
<commons.io.version>2.11.0</commons.io.version>
<commons.collections.version>3.2.2</commons.collections.version>
<poi.version>4.1.2</poi.version>
@ -200,6 +200,13 @@
<version>${ruoyi.version}</version>
</dependency>
<!-- knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<!-- 集成第三方登录 -->
<dependency>
<groupId>com.ruoyi</groupId>
@ -220,11 +227,11 @@
<version>6.0.0</version>
</dependency>
<!-- knife4j -->
<!-- 在线接口 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-online</artifactId>
<version>${ruoyi.version}</version>
</dependency>
</dependencies>
@ -239,6 +246,7 @@
<module>ruoyi-common</module>
<module>ruoyi-oauth</module>
<module>ruoyi-pay</module>
<module>ruoyi-online</module>
</modules>
<packaging>pom</packaging>

View File

@ -15,13 +15,11 @@
web服务入口
</description>
<dependencies>
<!-- 注入冲突 -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency> -->
<properties>
<ruoyi.version>3.8.7.3.1</ruoyi.version>
</properties>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
@ -58,7 +56,13 @@
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-oauth-wx</artifactId>
<version>3.8.7.3.1</version>
<version>${ruoyi.version}</version>
</dependency>
<!-- 在线接口 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-online</artifactId>
</dependency>
</dependencies>

View File

@ -11,14 +11,17 @@ import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
@ -74,7 +77,7 @@ public class HttpUtils
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
@ -136,7 +139,7 @@ public class HttpUtils
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
@ -202,7 +205,7 @@ public class HttpUtils
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);

View File

@ -1,31 +1,34 @@
package com.ruoyi.framework.security.handle;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* 自定义退出处理类 返回成功
*
* @author ruoyi
*/
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
@Autowired
private TokenService tokenService;
@ -36,17 +39,17 @@ public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
*/
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException
{
throws IOException, ServletException {
LoginUser loginUser = tokenService.getLoginUser(request);
if (StringUtils.isNotNull(loginUser))
{
if (StringUtils.isNotNull(loginUser)) {
String userName = loginUser.getUsername();
// 删除用户缓存记录
tokenService.delLoginUser(loginUser.getToken());
// 记录用户退出日志
AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT,
MessageUtils.message("user.logout.success")));
}
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("退出成功")));
ServletUtils.renderString(response,
JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
}
}

View File

@ -27,7 +27,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
select#foreach($column in $columns) #if($column.subColumnTableName)${column.subColumnTableName}.${column.subColumnName},#end${tableName}.${column.columnName}#if($foreach.count != $columns.size()),#end#end from ${tableName}
#foreach($column in $columns)
#if($column.subColumnTableName)
left join ${column.subColumnTableName} on ${column.subColumnTableName}.${column.subColumnName}=${tableName}.${column.columnName}
left join ${column.subColumnTableName} on ${column.subColumnTableName}.${column.subColumnFkName}=${tableName}.${column.columnName}
#end
#end
#else

28
ruoyi-online/pom.xml Normal file
View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.8.7.3.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-online</artifactId>
<description>
online系统模块
</description>
<dependencies>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,68 @@
package com.ruoyi.online.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.online.domain.OnlineMb;
import com.ruoyi.online.service.IOnlineMbService;
import com.ruoyi.online.utils.SqlMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@RestController
@Anonymous
@RequestMapping("/online")
public class OnLineController extends BaseController {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Autowired
private IOnlineMbService onlineMbService;
@PostMapping("/api/**")
public Object api(@RequestBody(required = false) Map<String, Object> data, HttpServletResponse response,
HttpServletRequest request) {
OnlineMb selectOnlineMb = new OnlineMb();
selectOnlineMb.setPath(request.getRequestURI().replace("/online/api", ""));
selectOnlineMb.setMethod(request.getMethod());
Map<String, Object> object = new HashMap<>();
Map<String, String[]> params = request.getParameterMap();
if (params != null) {
object.putAll(params);
}
if (data != null) {
object.putAll(data);
}
List<OnlineMb> selectOnlineMbList = onlineMbService.selectOnlineMbList(selectOnlineMb);
if (selectOnlineMbList.size() == 0) {
return error("没有相关接口");
} else if (selectOnlineMbList.size() > 1) {
return error("存在多个接口");
} else {
OnlineMb onlineMb = selectOnlineMbList.get(0);
String sql = "<script>" + onlineMb.getSql() + "</script>";
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlMapper sqlMapper = new SqlMapper(sqlSession);
return switch (onlineMb.getActuator()) {
case "selectList" -> getDataTable(sqlMapper.selectList(sql, object));
case "insert" -> toAjax(sqlMapper.insert(sql, object));
case "selectOne" -> success(sqlMapper.selectOne(sql, object));
case "update" -> toAjax(sqlMapper.update(sql, object));
case "delete" -> toAjax(sqlMapper.delete(sql, object));
default -> error("错误的执行器");
};
}
}
}

View File

@ -0,0 +1,113 @@
package com.ruoyi.online.controller;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.online.domain.OnlineMb;
import com.ruoyi.online.service.IOnlineMbService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
/**
* mybatis在线接口Controller
*
* @author ruoyi
* @date 2024-01-26
*/
@RestController
@RequestMapping("/online/mb")
@Tag(name = "【mybatis在线接口】管理")
public class OnlineMbController extends BaseController
{
@Autowired
private IOnlineMbService onlineMbService;
/**
* 查询mybatis在线接口列表
*/
@Operation(summary = "查询mybatis在线接口列表")
@PreAuthorize("@ss.hasPermi('online:mb:list')")
@GetMapping("/list")
public TableDataInfo list(OnlineMb onlineMb)
{
startPage();
List<OnlineMb> list = onlineMbService.selectOnlineMbList(onlineMb);
return getDataTable(list);
}
/**
* 导出mybatis在线接口列表
*/
@Operation(summary = "导出mybatis在线接口列表")
@PreAuthorize("@ss.hasPermi('online:mb:export')")
@Log(title = "mybatis在线接口", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, OnlineMb onlineMb)
{
List<OnlineMb> list = onlineMbService.selectOnlineMbList(onlineMb);
ExcelUtil<OnlineMb> util = new ExcelUtil<OnlineMb>(OnlineMb.class);
util.exportExcel(response, list, "mybatis在线接口数据");
}
/**
* 获取mybatis在线接口详细信息
*/
@Operation(summary = "获取mybatis在线接口详细信息")
@PreAuthorize("@ss.hasPermi('online:mb:query')")
@GetMapping(value = "/{mbId}")
public AjaxResult getInfo(@PathVariable("mbId") Long mbId)
{
return success(onlineMbService.selectOnlineMbByMbId(mbId));
}
/**
* 新增mybatis在线接口
*/
@Operation(summary = "新增mybatis在线接口")
@PreAuthorize("@ss.hasPermi('online:mb:add')")
@Log(title = "mybatis在线接口", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody OnlineMb onlineMb)
{
return toAjax(onlineMbService.insertOnlineMb(onlineMb));
}
/**
* 修改mybatis在线接口
*/
@Operation(summary = "修改mybatis在线接口")
@PreAuthorize("@ss.hasPermi('online:mb:edit')")
@Log(title = "mybatis在线接口", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody OnlineMb onlineMb)
{
return toAjax(onlineMbService.updateOnlineMb(onlineMb));
}
/**
* 删除mybatis在线接口
*/
@Operation(summary = "删除mybatis在线接口")
@PreAuthorize("@ss.hasPermi('online:mb:remove')")
@Log(title = "mybatis在线接口", businessType = BusinessType.DELETE)
@DeleteMapping("/{mbIds}")
public AjaxResult remove(@PathVariable( name = "mbIds" ) Long[] mbIds)
{
return toAjax(onlineMbService.deleteOnlineMbByMbIds(mbIds));
}
}

View File

@ -0,0 +1,227 @@
package com.ruoyi.online.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* mybatis在线接口对象 online_mb
*
* @author ruoyi
* @date 2024-01-26
*/
@Schema(description = "mybatis在线接口对象")
public class OnlineMb extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
@Schema(defaultValue = "主键")
private Long mbId;
/** 标签名 */
@Schema(defaultValue = "标签名")
@Excel(name = "标签名")
private String tag;
/** 标签id */
@Schema(defaultValue = "标签id")
@Excel(name = "标签id")
private String tagId;
/** 参数类型 */
@Schema(defaultValue = "参数类型")
@Excel(name = "参数类型")
private String parameterType;
/** 结果类型 */
@Schema(defaultValue = "结果类型")
@Excel(name = "结果类型")
private String resultMap;
/** sql语句 */
@Schema(defaultValue = "sql语句")
@Excel(name = "sql语句")
private String sql;
/** 请求路径 */
@Schema(defaultValue = "请求路径")
@Excel(name = "请求路径")
private String path;
/** 请求方式 */
@Schema(defaultValue = "请求方式")
@Excel(name = "请求方式")
private String method;
/** 响应类型 */
@Schema(defaultValue = "响应类型")
@Excel(name = "响应类型")
private String resultType;
/** 执行器 */
@Schema(defaultValue = "执行器")
@Excel(name = "执行器")
private String actuator;
public void setMbId(Long mbId)
{
this.mbId = mbId;
}
public Long getMbId()
{
return mbId;
}
public void setTag(String tag)
{
this.tag = tag;
}
public String getTag()
{
return tag;
}
public void setTagId(String tagId)
{
this.tagId = tagId;
}
public String getTagId()
{
return tagId;
}
public void setParameterType(String parameterType)
{
this.parameterType = parameterType;
}
public String getParameterType()
{
return parameterType;
}
public void setResultMap(String resultMap)
{
this.resultMap = resultMap;
}
public String getResultMap()
{
return resultMap;
}
public void setSql(String sql)
{
this.sql = sql;
}
public String getSql()
{
return sql;
}
public void setPath(String path)
{
this.path = path;
}
public String getPath()
{
return path;
}
public void setMethod(String method)
{
this.method = method;
}
public String getMethod()
{
return method;
}
public void setResultType(String resultType)
{
this.resultType = resultType;
}
public String getResultType()
{
return resultType;
}
public void setActuator(String actuator)
{
this.actuator = actuator;
}
public String getActuator()
{
return actuator;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("mbId", getMbId())
.append("tag", getTag())
.append("tagId", getTagId())
.append("parameterType", getParameterType())
.append("resultMap", getResultMap())
.append("sql", getSql())
.append("path", getPath())
.append("method", getMethod())
.append("resultType", getResultType())
.append("actuator", getActuator())
.toString();
}
}

View File

@ -0,0 +1,61 @@
package com.ruoyi.online.mapper;
import java.util.List;
import com.ruoyi.online.domain.OnlineMb;
/**
* mybatis在线接口Mapper接口
*
* @author ruoyi
* @date 2024-01-26
*/
public interface OnlineMbMapper
{
/**
* 查询mybatis在线接口
*
* @param mbId mybatis在线接口主键
* @return mybatis在线接口
*/
public OnlineMb selectOnlineMbByMbId(Long mbId);
/**
* 查询mybatis在线接口列表
*
* @param onlineMb mybatis在线接口
* @return mybatis在线接口集合
*/
public List<OnlineMb> selectOnlineMbList(OnlineMb onlineMb);
/**
* 新增mybatis在线接口
*
* @param onlineMb mybatis在线接口
* @return 结果
*/
public int insertOnlineMb(OnlineMb onlineMb);
/**
* 修改mybatis在线接口
*
* @param onlineMb mybatis在线接口
* @return 结果
*/
public int updateOnlineMb(OnlineMb onlineMb);
/**
* 删除mybatis在线接口
*
* @param mbId mybatis在线接口主键
* @return 结果
*/
public int deleteOnlineMbByMbId(Long mbId);
/**
* 批量删除mybatis在线接口
*
* @param mbIds 需要删除的数据主键集合
* @return 结果
*/
public int deleteOnlineMbByMbIds(Long[] mbIds);
}

View File

@ -0,0 +1,61 @@
package com.ruoyi.online.service;
import java.util.List;
import com.ruoyi.online.domain.OnlineMb;
/**
* mybatis在线接口Service接口
*
* @author ruoyi
* @date 2024-01-26
*/
public interface IOnlineMbService
{
/**
* 查询mybatis在线接口
*
* @param mbId mybatis在线接口主键
* @return mybatis在线接口
*/
public OnlineMb selectOnlineMbByMbId(Long mbId);
/**
* 查询mybatis在线接口列表
*
* @param onlineMb mybatis在线接口
* @return mybatis在线接口集合
*/
public List<OnlineMb> selectOnlineMbList(OnlineMb onlineMb);
/**
* 新增mybatis在线接口
*
* @param onlineMb mybatis在线接口
* @return 结果
*/
public int insertOnlineMb(OnlineMb onlineMb);
/**
* 修改mybatis在线接口
*
* @param onlineMb mybatis在线接口
* @return 结果
*/
public int updateOnlineMb(OnlineMb onlineMb);
/**
* 批量删除mybatis在线接口
*
* @param mbIds 需要删除的mybatis在线接口主键集合
* @return 结果
*/
public int deleteOnlineMbByMbIds(Long[] mbIds);
/**
* 删除mybatis在线接口信息
*
* @param mbId mybatis在线接口主键
* @return 结果
*/
public int deleteOnlineMbByMbId(Long mbId);
}

View File

@ -0,0 +1,93 @@
package com.ruoyi.online.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.online.mapper.OnlineMbMapper;
import com.ruoyi.online.domain.OnlineMb;
import com.ruoyi.online.service.IOnlineMbService;
/**
* mybatis在线接口Service业务层处理
*
* @author ruoyi
* @date 2024-01-26
*/
@Service
public class OnlineMbServiceImpl implements IOnlineMbService
{
@Autowired
private OnlineMbMapper onlineMbMapper;
/**
* 查询mybatis在线接口
*
* @param mbId mybatis在线接口主键
* @return mybatis在线接口
*/
@Override
public OnlineMb selectOnlineMbByMbId(Long mbId)
{
return onlineMbMapper.selectOnlineMbByMbId(mbId);
}
/**
* 查询mybatis在线接口列表
*
* @param onlineMb mybatis在线接口
* @return mybatis在线接口
*/
@Override
public List<OnlineMb> selectOnlineMbList(OnlineMb onlineMb)
{
return onlineMbMapper.selectOnlineMbList(onlineMb);
}
/**
* 新增mybatis在线接口
*
* @param onlineMb mybatis在线接口
* @return 结果
*/
@Override
public int insertOnlineMb(OnlineMb onlineMb)
{
return onlineMbMapper.insertOnlineMb(onlineMb);
}
/**
* 修改mybatis在线接口
*
* @param onlineMb mybatis在线接口
* @return 结果
*/
@Override
public int updateOnlineMb(OnlineMb onlineMb)
{
return onlineMbMapper.updateOnlineMb(onlineMb);
}
/**
* 批量删除mybatis在线接口
*
* @param mbIds 需要删除的mybatis在线接口主键
* @return 结果
*/
@Override
public int deleteOnlineMbByMbIds(Long[] mbIds)
{
return onlineMbMapper.deleteOnlineMbByMbIds(mbIds);
}
/**
* 删除mybatis在线接口信息
*
* @param mbId mybatis在线接口主键
* @return 结果
*/
@Override
public int deleteOnlineMbByMbId(Long mbId)
{
return onlineMbMapper.deleteOnlineMbByMbId(mbId);
}
}

View File

@ -0,0 +1,411 @@
package com.ruoyi.online.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
/**
* MyBatis执行sql工具在写SQL的时候建议使用参数形式的可以是${}#{}
*
* 不建议将参数直接拼到字符串中当大量这么使用的时候由于缓存MappedStatement而占用更多的内存
*
* @author liuzh
* @since 2015-03-10
*/
public class SqlMapper {
private final MSUtils msUtils;
private final SqlSession sqlSession;
/**
* 构造方法默认缓存MappedStatement
*
* @param sqlSession
*/
public SqlMapper(SqlSession sqlSession) {
this.sqlSession = sqlSession;
this.msUtils = new MSUtils(sqlSession.getConfiguration());
}
/**
* 获取List中最多只有一个的数据
*
* @param list List结果
* @param <T> 泛型类型
* @return
*/
private <T> T getOne(List<T> list) {
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
/**
* 查询返回一个结果多个结果时抛出异常
*
* @param sql 执行的sql
* @return
*/
public Map<String, Object> selectOne(String sql) {
List<Map<String, Object>> list = selectList(sql);
return getOne(list);
}
/**
* 查询返回一个结果多个结果时抛出异常
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public Map<String, Object> selectOne(String sql, Object value) {
List<Map<String, Object>> list = selectList(sql, value);
return getOne(list);
}
/**
* 查询返回一个结果多个结果时抛出异常
*
* @param sql 执行的sql
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> T selectOne(String sql, Class<T> resultType) {
List<T> list = selectList(sql, resultType);
return getOne(list);
}
/**
* 查询返回一个结果多个结果时抛出异常
*
* @param sql 执行的sql
* @param value 参数
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> T selectOne(String sql, Object value, Class<T> resultType) {
List<T> list = selectList(sql, value, resultType);
return getOne(list);
}
/**
* 查询返回List<Map<String, Object>>
*
* @param sql 执行的sql
* @return
*/
public List<Map<String, Object>> selectList(String sql) {
String msId = msUtils.select(sql);
return sqlSession.selectList(msId);
}
/**
* 查询返回List<Map<String, Object>>
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public List<Map<String, Object>> selectList(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.selectDynamic(sql, parameterType);
return sqlSession.selectList(msId, value);
}
/**
* 查询返回指定的结果类型
*
* @param sql 执行的sql
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> List<T> selectList(String sql, Class<T> resultType) {
String msId;
if (resultType == null) {
msId = msUtils.select(sql);
} else {
msId = msUtils.select(sql, resultType);
}
return sqlSession.selectList(msId);
}
/**
* 查询返回指定的结果类型
*
* @param sql 执行的sql
* @param value 参数
* @param resultType 返回的结果类型
* @param <T> 泛型类型
* @return
*/
public <T> List<T> selectList(String sql, Object value, Class<T> resultType) {
String msId;
Class<?> parameterType = value != null ? value.getClass() : null;
if (resultType == null) {
msId = msUtils.selectDynamic(sql, parameterType);
} else {
msId = msUtils.selectDynamic(sql, parameterType, resultType);
}
return sqlSession.selectList(msId, value);
}
/**
* 插入数据
*
* @param sql 执行的sql
* @return
*/
public int insert(String sql) {
String msId = msUtils.insert(sql);
return sqlSession.insert(msId);
}
/**
* 插入数据
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public int insert(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.insertDynamic(sql, parameterType);
return sqlSession.insert(msId, value);
}
/**
* 更新数据
*
* @param sql 执行的sql
* @return
*/
public int update(String sql) {
String msId = msUtils.update(sql);
return sqlSession.update(msId);
}
/**
* 更新数据
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public int update(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.updateDynamic(sql, parameterType);
return sqlSession.update(msId, value);
}
/**
* 删除数据
*
* @param sql 执行的sql
* @return
*/
public int delete(String sql) {
String msId = msUtils.delete(sql);
return sqlSession.delete(msId);
}
/**
* 删除数据
*
* @param sql 执行的sql
* @param value 参数
* @return
*/
public int delete(String sql, Object value) {
Class<?> parameterType = value != null ? value.getClass() : null;
String msId = msUtils.deleteDynamic(sql, parameterType);
return sqlSession.delete(msId, value);
}
private class MSUtils {
private Configuration configuration;
private LanguageDriver languageDriver;
private MSUtils(Configuration configuration) {
this.configuration = configuration;
languageDriver = configuration.getDefaultScriptingLanuageInstance();
}
/**
* 创建MSID
*
* @param sql 执行的sql
* @param sql 执行的sqlCommandType
* @return
*/
private String newMsId(String sql, SqlCommandType sqlCommandType) {
StringBuilder msIdBuilder = new StringBuilder(sqlCommandType.toString());
msIdBuilder.append(".").append(sql.hashCode());
return msIdBuilder.toString();
}
/**
* 是否已经存在该ID
*
* @param msId
* @return
*/
private boolean hasMappedStatement(String msId) {
return configuration.hasStatement(msId, false);
}
/**
* 创建一个查询的MS
*
* @param msId
* @param sqlSource 执行的sqlSource
* @param resultType 返回的结果类型
*/
private void newSelectMappedStatement(String msId, SqlSource sqlSource, final Class<?> resultType) {
MappedStatement ms = new MappedStatement.Builder(configuration, msId, sqlSource, SqlCommandType.SELECT)
.resultMaps(new ArrayList<ResultMap>() {
{
add(new ResultMap.Builder(configuration, "defaultResultMap", resultType, new ArrayList<ResultMapping>(0)).build());
}
})
.build();
//缓存
configuration.addMappedStatement(ms);
}
/**
* 创建一个简单的MS
*
* @param msId
* @param sqlSource 执行的sqlSource
* @param sqlCommandType 执行的sqlCommandType
*/
private void newUpdateMappedStatement(String msId, SqlSource sqlSource, SqlCommandType sqlCommandType) {
MappedStatement ms = new MappedStatement.Builder(configuration, msId, sqlSource, sqlCommandType)
.resultMaps(new ArrayList<ResultMap>() {
{
add(new ResultMap.Builder(configuration, "defaultResultMap", int.class, new ArrayList<ResultMapping>(0)).build());
}
})
.build();
//缓存
configuration.addMappedStatement(ms);
}
private String select(String sql) {
String msId = newMsId(sql, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newSelectMappedStatement(msId, sqlSource, Map.class);
return msId;
}
private String selectDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newSelectMappedStatement(msId, sqlSource, Map.class);
return msId;
}
private String select(String sql, Class<?> resultType) {
String msId = newMsId(resultType + sql, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newSelectMappedStatement(msId, sqlSource, resultType);
return msId;
}
private String selectDynamic(String sql, Class<?> parameterType, Class<?> resultType) {
String msId = newMsId(resultType + sql + parameterType, SqlCommandType.SELECT);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newSelectMappedStatement(msId, sqlSource, resultType);
return msId;
}
private String insert(String sql) {
String msId = newMsId(sql, SqlCommandType.INSERT);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.INSERT);
return msId;
}
private String insertDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.INSERT);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.INSERT);
return msId;
}
private String update(String sql) {
String msId = newMsId(sql, SqlCommandType.UPDATE);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.UPDATE);
return msId;
}
private String updateDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.UPDATE);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.UPDATE);
return msId;
}
private String delete(String sql) {
String msId = newMsId(sql, SqlCommandType.DELETE);
if (hasMappedStatement(msId)) {
return msId;
}
StaticSqlSource sqlSource = new StaticSqlSource(configuration, sql);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.DELETE);
return msId;
}
private String deleteDynamic(String sql, Class<?> parameterType) {
String msId = newMsId(sql + parameterType, SqlCommandType.DELETE);
if (hasMappedStatement(msId)) {
return msId;
}
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, parameterType);
newUpdateMappedStatement(msId, sqlSource, SqlCommandType.DELETE);
return msId;
}
}
}

View File

@ -0,0 +1,98 @@
<?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.ruoyi.online.mapper.OnlineMbMapper">
<resultMap type="OnlineMb" id="OnlineMbResult">
<result property="mbId" column="mb_id" />
<result property="tag" column="tag" />
<result property="tagId" column="tag_id" />
<result property="parameterType" column="parameterType" />
<result property="resultMap" column="resultMap" />
<result property="sql" column="sql" />
<result property="path" column="path" />
<result property="method" column="method" />
<result property="resultType" column="resultType" />
<result property="actuator" column="actuator" />
</resultMap>
<sql id="selectOnlineMbVo">
select mb_id, tag, tag_id, parameterType, resultMap, `sql`, `path`, method, resultType, actuator from online_mb
</sql>
<select id="selectOnlineMbList" parameterType="OnlineMb" resultMap="OnlineMbResult">
<include refid="selectOnlineMbVo"/>
<where>
<if test="tag != null and tag != ''"> and tag = #{tag}</if>
<if test="tagId != null and tagId != ''"> and tag_id = #{tagId}</if>
<if test="parameterType != null and parameterType != ''"> and parameterType = #{parameterType}</if>
<if test="resultMap != null and resultMap != ''"> and resultMap = #{resultMap}</if>
<if test="sql != null and sql != ''"> and `sql` = #{sql}</if>
<if test="path != null and path != ''"> and `path` = #{path}</if>
<if test="method != null and method != ''"> and method = #{method}</if>
<if test="resultType != null and resultType != ''"> and resultType = #{resultType}</if>
<if test="actuator != null and actuator != ''"> and actuator = #{actuator}</if>
</where>
</select>
<select id="selectOnlineMbByMbId" parameterType="Long" resultMap="OnlineMbResult">
<include refid="selectOnlineMbVo"/>
where online_mb.mb_id = #{mbId}
</select>
<insert id="insertOnlineMb" parameterType="OnlineMb">
insert into online_mb
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="mbId != null">mb_id,</if>
<if test="tag != null">tag,</if>
<if test="tagId != null">tag_id,</if>
<if test="parameterType != null">parameterType,</if>
<if test="resultMap != null">resultMap,</if>
<if test="sql != null">sql,</if>
<if test="path != null and path != ''">path,</if>
<if test="method != null and method != ''">method,</if>
<if test="resultType != null">resultType,</if>
<if test="actuator != null and actuator != ''">actuator,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="mbId != null">#{mbId},</if>
<if test="tag != null">#{tag},</if>
<if test="tagId != null">#{tagId},</if>
<if test="parameterType != null">#{parameterType},</if>
<if test="resultMap != null">#{resultMap},</if>
<if test="sql != null">#{sql},</if>
<if test="path != null and path != ''">#{path},</if>
<if test="method != null and method != ''">#{method},</if>
<if test="resultType != null">#{resultType},</if>
<if test="actuator != null and actuator != ''">#{actuator},</if>
</trim>
</insert>
<update id="updateOnlineMb" parameterType="OnlineMb">
update online_mb
<trim prefix="SET" suffixOverrides=",">
<if test="tag != null">tag = #{tag},</if>
<if test="tagId != null">tag_id = #{tagId},</if>
<if test="parameterType != null">parameterType = #{parameterType},</if>
<if test="resultMap != null">resultMap = #{resultMap},</if>
<if test="sql != null">`sql` = #{sql},</if>
<if test="path != null and path != ''">`path` = #{path},</if>
<if test="method != null and method != ''">method = #{method},</if>
<if test="resultType != null">resultType = #{resultType},</if>
<if test="actuator != null and actuator != ''">actuator = #{actuator},</if>
</trim>
where online_mb.mb_id = #{mbId}
</update>
<delete id="deleteOnlineMbByMbId" parameterType="Long">
delete from online_mb where mb_id = #{mbId}
</delete>
<delete id="deleteOnlineMbByMbIds" parameterType="String">
delete from online_mb where mb_id in
<foreach item="mbId" collection="array" open="(" separator="," close=")">
#{mbId}
</foreach>
</delete>
</mapper>

38
sql/online.sql Normal file
View File

@ -0,0 +1,38 @@
DROP TABLE IF EXISTS `online_mb`;
CREATE TABLE `online_mb` (
`mb_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`tag` varchar(255) NULL COMMENT '标签名',
`tag_id` varchar(255) NULL COMMENT '标签id',
`parameterType` varchar(255) NULL COMMENT '参数类型',
`resultMap` varchar(255) NULL COMMENT '结果类型',
`sql` varchar(255) NULL COMMENT 'sql语句',
`path` varchar(255) NULL COMMENT '请求路径',
`method` varchar(255) NULL COMMENT '请求方式',
`resultType` varchar(255) NULL COMMENT '响应类型',
`actuator` varchar(255) NULL COMMENT '执行器',
PRIMARY KEY (`mb_id`)
);
-- 菜单 SQL
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('mybatis在线接口', '3', '1', 'mb', 'tool/online/mb/index', 1, 0, 'C', '0', '0', 'online:mb:list', 'code', 'admin', sysdate(), '', null, 'mybatis在线接口菜单');
-- 按钮父菜单ID
SELECT @parentId := LAST_INSERT_ID();
-- 按钮 SQL
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('mybatis在线接口查询', @parentId, '1', '#', '', 1, 0, 'F', '0', '0', 'online:mb:query', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('mybatis在线接口新增', @parentId, '2', '#', '', 1, 0, 'F', '0', '0', 'online:mb:add', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('mybatis在线接口修改', @parentId, '3', '#', '', 1, 0, 'F', '0', '0', 'online:mb:edit', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('mybatis在线接口删除', @parentId, '4', '#', '', 1, 0, 'F', '0', '0', 'online:mb:remove', '#', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values('mybatis在线接口导出', @parentId, '5', '#', '', 1, 0, 'F', '0', '0', 'online:mb:export', '#', 'admin', sysdate(), '', null, '');