创建框架整合版本
This commit is contained in:
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
## ide
|
||||
**/.idea
|
||||
*.iml
|
||||
|
||||
## backend
|
||||
**/target
|
||||
**/logs
|
||||
**/log
|
||||
|
||||
## front
|
||||
**/*.lock
|
||||
187
hcframe-parent/hcframe-base/pom.xml
Normal file
187
hcframe-parent/hcframe-base/pom.xml
Normal file
@@ -0,0 +1,187 @@
|
||||
<?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>parent</artifactId>
|
||||
<groupId>com.hcframe</groupId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>hcframe-base</artifactId>
|
||||
<version>1.2.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>8</maven.compiler.source>
|
||||
<maven.compiler.target>8</maven.compiler.target>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>2.1.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
<scope>runtime</scope>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjrt</artifactId>
|
||||
<version>1.8.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.70</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-spring-boot-starter</artifactId>
|
||||
<version>2.0.2</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>2.0.1.Final</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.shiro</groupId>
|
||||
<artifactId>shiro-spring</artifactId>
|
||||
<version>1.3.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.10</version><!--$NO-MVN-MAN-VER$-->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>1.4.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>tk.mybatis</groupId>
|
||||
<artifactId>mapper-spring-boot-starter</artifactId>
|
||||
<version>2.1.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>1.2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.pagehelper</groupId>
|
||||
<artifactId>pagehelper-spring-boot-starter</artifactId>
|
||||
<version>1.2.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
<version>2.6.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.14</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>25.1-jre</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
|
||||
<dependency>
|
||||
<groupId>org.xerial</groupId>
|
||||
<artifactId>sqlite-jdbc</artifactId>
|
||||
<version>3.32.3.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<!-- 缓存 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-cache</artifactId>
|
||||
</dependency>
|
||||
<!-- ehcache -->
|
||||
<dependency>
|
||||
<groupId>net.sf.ehcache</groupId>
|
||||
<artifactId>ehcache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.dm</groupId>
|
||||
<artifactId>Dm7JdbcDriver</artifactId>
|
||||
<version>1.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.oracle</groupId>
|
||||
<artifactId>ojdbc6</artifactId>
|
||||
<version>11.2.0.4</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<finalName>hcframe-base</finalName>
|
||||
<plugins>
|
||||
<!-- <plugin>-->
|
||||
<!-- <groupId>org.springframework.boot</groupId>-->
|
||||
<!-- <artifactId>spring-boot-maven-plugin</artifactId>-->
|
||||
<!-- <configuration>-->
|
||||
<!-- <includeSystemScope>true</includeSystemScope>-->
|
||||
<!-- </configuration>-->
|
||||
<!-- </plugin>-->
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
||||
import org.apache.shiro.authz.AuthorizationException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
/***
|
||||
* @description 异常信息拦截类,如果程序运行过程中抛出异常,会将异常拦截下来,并返回前端一个包含异常信息的Json数据
|
||||
*/
|
||||
|
||||
@ControllerAdvice
|
||||
public class ControllerExceptionHandler {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseBody
|
||||
public ResultVO handleServiceException(
|
||||
Exception e) {
|
||||
if (e instanceof AuthorizationException) {
|
||||
return ResultVO.getNoAuthorization();
|
||||
} else if (e instanceof AuthenticationException) {
|
||||
return ResultVO.getFailed("用户名或密码错误");
|
||||
} else if (e instanceof RuntimeException) {
|
||||
System.out.println("handleServiceException");
|
||||
e.printStackTrace();
|
||||
//封装错误信息
|
||||
return ResultVO.getException(e);
|
||||
} else {
|
||||
return ResultVO.getException(e);
|
||||
}
|
||||
}
|
||||
//.......
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
import tk.mybatis.mapper.common.*;
|
||||
|
||||
/***
|
||||
* @description 调用tkmapper进行接口封装
|
||||
* @param <T>
|
||||
*/
|
||||
public interface Mapper<T> extends
|
||||
BaseMapper<T>,
|
||||
ExampleMapper<T>,
|
||||
RowBoundsMapper<T>,
|
||||
Marker, ConditionMapper<T>, tk.mybatis.mapper.common.Mapper<T> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/***
|
||||
* @description 异常信息拦截类,如果程序运行过程中抛出异常,会将异常拦截下来,并返回前端一个包含异常信息的Json数据
|
||||
*/
|
||||
|
||||
@RestControllerAdvice
|
||||
public class RestControllerExceptionHandler {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResultVO handleServiceException(
|
||||
RuntimeException e){
|
||||
e.printStackTrace();
|
||||
//封装错误信息
|
||||
return ResultVO.getException(e);
|
||||
}
|
||||
//.......
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
public class ResultPageInfo<T> {
|
||||
|
||||
private List<T> list;
|
||||
|
||||
private long total;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @description 返回结果VO对象
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class ResultVO<T> {
|
||||
|
||||
private static final Integer SUCCESS = 0;
|
||||
private static final Integer FAILED = 1;
|
||||
private static final Integer ERROR = 2;
|
||||
private static final Integer UNLOG = 3;
|
||||
private static final Integer NOAUTH = 4;
|
||||
//("状态码 0成功 1失败 2服务器出错 3未登录 4没有权限")
|
||||
private Integer code=SUCCESS;
|
||||
|
||||
//("返回信息")
|
||||
@ApiModelProperty(example="ActionOK")
|
||||
private String msg;
|
||||
|
||||
//("返回数据")
|
||||
private T data;
|
||||
|
||||
private ResultVO() {
|
||||
this.code = SUCCESS;
|
||||
this.msg = "Action OK";
|
||||
}
|
||||
private ResultVO(T data) {
|
||||
this.code = SUCCESS;
|
||||
this.msg = "Action OK";
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
private ResultVO(Integer code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
private ResultVO(Integer code, String msg, T data) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
private ResultVO(Throwable exp){
|
||||
this.code=ERROR;
|
||||
this.msg=exp.getMessage();
|
||||
}
|
||||
/**
|
||||
* 请求成功 状态码 1
|
||||
*
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getSuccess(T data) {
|
||||
return new ResultVO<>(data);
|
||||
}
|
||||
/**
|
||||
* 请求成功 状态码 1
|
||||
*
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getSuccess() {
|
||||
return new ResultVO<>();
|
||||
}
|
||||
/**
|
||||
* 请求成功 状态码 1
|
||||
*
|
||||
* @param msg 返回信息
|
||||
* @param data 返回对象
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getSuccess(String msg, T data) {
|
||||
return new ResultVO<T>(SUCCESS, msg, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求失败 状态码 0
|
||||
*
|
||||
* @param msg 返回信息
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getFailed(String msg) {
|
||||
return new ResultVO<>(FAILED, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求失败 状态 0
|
||||
*
|
||||
* @param msg 返回信息
|
||||
* @param data 返回数据
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getFailed(String msg, T data) {
|
||||
return new ResultVO<>(FAILED, msg, data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 用户未登录
|
||||
*
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getNoLogin() {
|
||||
return new ResultVO<T>(UNLOG, "用户未登录,请重新登录");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 用户没有操作权限
|
||||
*
|
||||
* @param <T> 类型
|
||||
* @return ResultVO
|
||||
*/
|
||||
public static <T> ResultVO<T> getNoAuthorization() {
|
||||
return new ResultVO<T>(NOAUTH, "用户没有操作权限,请重新登录");
|
||||
}
|
||||
|
||||
public static <T> ResultVO<T> getException(Throwable exp) {
|
||||
return new ResultVO<T>(exp);
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(Integer code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
/***
|
||||
* @description 自定义异常类
|
||||
*/
|
||||
public class ServiceException extends RuntimeException {
|
||||
|
||||
public ServiceException() {
|
||||
|
||||
}
|
||||
|
||||
public ServiceException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ServiceException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public ServiceException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.hcframe.base.common;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* (WebPageInfo)实体类
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-02-11 19:29:10
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
@ApiModel
|
||||
public class WebPageInfo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1156251348750279606L;
|
||||
|
||||
public static final String DESC = "desc";
|
||||
public static final String ASC = "asc";
|
||||
|
||||
@ApiModelProperty(
|
||||
value="每页显示条数" ,
|
||||
example="10",
|
||||
dataType = "Integer"
|
||||
)
|
||||
private Integer pageSize = 10;
|
||||
|
||||
@ApiModelProperty(
|
||||
value="页码" ,
|
||||
example="1",
|
||||
dataType = "Integer"
|
||||
)
|
||||
private Integer pageNum = 1;
|
||||
|
||||
@ApiModelProperty(value="排序字段")
|
||||
private String sortField;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "正序倒序",
|
||||
allowableValues = "asc,desc",
|
||||
example = "asc")
|
||||
private String order = ASC;
|
||||
|
||||
public static boolean hasSort(WebPageInfo webPageInfo) {
|
||||
return !StringUtils.isBlank(webPageInfo.getSortField());
|
||||
}
|
||||
|
||||
public String getSortSql() {
|
||||
return this.sortField + " " + this.order;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "frame")
|
||||
public class FrameConfig {
|
||||
private Boolean isRedisLogin = false;
|
||||
private Integer loginTimeout = 4;
|
||||
private Boolean showControllerLog = true;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.websocket.HandshakeResponse;
|
||||
import javax.websocket.server.HandshakeRequest;
|
||||
import javax.websocket.server.ServerEndpointConfig;
|
||||
import javax.websocket.server.ServerEndpointConfig.Configurator;
|
||||
/*
|
||||
* 获取HttpSession
|
||||
*
|
||||
*/
|
||||
|
||||
public class GetHttpSession extends Configurator {
|
||||
|
||||
@Override
|
||||
public void modifyHandshake(ServerEndpointConfig sec,
|
||||
HandshakeRequest request, HandshakeResponse response) {
|
||||
HttpSession httpSession=(HttpSession) request.getHttpSession();
|
||||
sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/**
|
||||
* @description redis配置类
|
||||
* @author lhc
|
||||
* @date 2020-06-15
|
||||
*/
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
/**
|
||||
* springboot2.x 使用LettuceConnectionFactory 代替 RedisConnectionFactory
|
||||
* application.yml配置基本信息后,springboot2.x RedisAutoConfiguration能够自动装配
|
||||
* LettuceConnectionFactory 和 RedisConnectionFactory 及其 RedisTemplate
|
||||
* @param redisConnectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
|
||||
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory);
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 跨域支持
|
||||
|
||||
*/
|
||||
@WebFilter
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class SimpleCORSFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
/*String[] whiteList = {"http://fwh.castscs.org.cn", "http://localhost"};
|
||||
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
|
||||
String myOrigin = httpServletRequest.getHeader("origin");
|
||||
boolean isValid = false;
|
||||
for( String ip : whiteList ) {
|
||||
if( myOrigin != null && myOrigin.equals(ip) ){
|
||||
isValid = true;
|
||||
break;
|
||||
}
|
||||
}*/
|
||||
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
|
||||
String myOrigin = httpServletRequest.getHeader("origin");
|
||||
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
|
||||
httpServletResponse.setHeader("Access-Control-Allow-Origin", myOrigin);
|
||||
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
|
||||
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
|
||||
httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with, X-Access-Token, datasource-Key");
|
||||
// 是否支持cookie跨域
|
||||
httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig arg0) throws ServletException {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
|
||||
import com.github.xiaoymin.knife4j.spring.filter.SecurityBasicAuthFilter;
|
||||
import io.swagger.annotations.Api;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
|
||||
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger2.annotations.EnableSwagger2;
|
||||
|
||||
@Configuration
|
||||
@EnableSwagger2
|
||||
@EnableKnife4j
|
||||
@Import(BeanValidatorPluginsConfiguration.class)
|
||||
public class SwaggerConfig extends WebMvcConfigurationSupport {
|
||||
|
||||
|
||||
@Bean
|
||||
@ConfigurationProperties(prefix = "swagger")
|
||||
public SwaggerEntity getSwaggerEntity() {
|
||||
return new SwaggerEntity();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Docket createRestApi() {
|
||||
SwaggerEntity swaggerEntity = getSwaggerEntity();
|
||||
return new Docket(DocumentationType.SWAGGER_2)
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
|
||||
.paths(PathSelectors.any())
|
||||
.build();
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder()
|
||||
.title("通用后台模板")
|
||||
.description("简单优雅的restfun风格")
|
||||
.termsOfServiceUrl("")
|
||||
.version("1.0")
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 防止@EnableMvc把默认的静态资源路径覆盖了,手动设置的方式
|
||||
*
|
||||
* @param registry
|
||||
*/
|
||||
@Override
|
||||
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
// 解决静态资源无法访问
|
||||
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
|
||||
// 解决swagger无法访问
|
||||
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
|
||||
// 解决swagger的js文件无法访问
|
||||
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
|
||||
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean SwaggerFilterRegistration() {
|
||||
FilterRegistrationBean registration = new FilterRegistrationBean(new SecurityBasicAuthFilter());
|
||||
registration.addUrlPatterns("/*");
|
||||
registration.setName("swaggerSecurityBasic");
|
||||
SwaggerEntity swaggerEntity = getSwaggerEntity();
|
||||
registration.addInitParameter("enableBasicAuth",swaggerEntity.enableAuth);
|
||||
if (SwaggerEntity.TRUE.equals(swaggerEntity.enableAuth)) {
|
||||
registration.addInitParameter("userName",swaggerEntity.username);
|
||||
registration.addInitParameter("password",swaggerEntity.password);
|
||||
}
|
||||
return registration;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SwaggerEntity {
|
||||
|
||||
public static final String TRUE = "true";
|
||||
public static final String FALSE = "false";
|
||||
|
||||
public String path;
|
||||
|
||||
public String enableAuth = FALSE;
|
||||
|
||||
public String username = "admin";
|
||||
|
||||
public String password = "123456";
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.FormContentFilter;
|
||||
|
||||
@Component
|
||||
public class WebMvcConfig extends FormContentFilter {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.hcframe.base.common.config;
|
||||
|
||||
import javax.servlet.ServletRequestEvent;
|
||||
import javax.servlet.ServletRequestListener;
|
||||
import javax.servlet.annotation.WebListener;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@WebListener
|
||||
public class webSessionListener implements ServletRequestListener {
|
||||
|
||||
@Override
|
||||
public void requestInitialized(ServletRequestEvent sre) {
|
||||
//将所有request请求都携带上httpSession
|
||||
((HttpServletRequest) sre.getServletRequest()).getSession();
|
||||
|
||||
}
|
||||
public webSessionListener() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void requestDestroyed(ServletRequestEvent arg0) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateUtil {
|
||||
|
||||
|
||||
/**
|
||||
* 日期格式化成字符串
|
||||
* @param date
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static String DateFormat(Date date,String format) {
|
||||
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
|
||||
LocalDateTime date1 = date2LocalDateTime(date);
|
||||
return date1.format(dtf);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串格式化成日期
|
||||
*/
|
||||
public static Date StringFormat(String string,String format) {
|
||||
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
|
||||
LocalDate localDate = LocalDate.parse(string,dtf);
|
||||
return localDate2Date(localDate);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Date转换为LocalDateTime
|
||||
* @param date
|
||||
*/
|
||||
public static LocalDateTime date2LocalDateTime(Date date){
|
||||
Instant instant = date.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
|
||||
ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
|
||||
return instant.atZone(zoneId).toLocalDateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalDateTime转换为Date
|
||||
* @param localDateTime
|
||||
*/
|
||||
public static Date localDateTime2Date( LocalDateTime localDateTime){
|
||||
ZoneId zoneId = ZoneId.systemDefault();
|
||||
ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a ZonedDateTime.
|
||||
return Date.from(zdt.toInstant());
|
||||
}
|
||||
|
||||
/**
|
||||
* localDate转Date
|
||||
*/
|
||||
public static Date localDate2Date(LocalDate localDate) {
|
||||
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
|
||||
Instant instant1 = zonedDateTime.toInstant();
|
||||
return Date.from(instant1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Date 转 localDate
|
||||
*/
|
||||
public static LocalDate date2LocalDate(Date date) {
|
||||
Instant instant = date.toInstant();
|
||||
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
|
||||
return zdt.toLocalDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字符串中的月份
|
||||
* @param str
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static int getStringMonth(String str,String format) {
|
||||
Date date=StringFormat(str, format);
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
return cal.get(Calendar.MONTH);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public class EmptyCheckUtils {
|
||||
|
||||
public static boolean checkWithException(Object object,String info){
|
||||
if (StringUtils.isEmpty(object)) {
|
||||
throw new ServiceException(info);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
|
||||
import org.apache.shiro.codec.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
public class EncryptUtil {
|
||||
public static final String MD5 = "MD5";
|
||||
public static final String SHA1 = "SHA1";
|
||||
public static final String HmacMD5 = "HmacMD5";
|
||||
public static final String HmacSHA1 = "HmacSHA1";
|
||||
public static final String DES = "DES";
|
||||
public static final String AES = "AES";
|
||||
|
||||
/**
|
||||
* 编码格式;默认使用uft-8
|
||||
*/
|
||||
public String charset = "utf-8";
|
||||
/**
|
||||
* DES
|
||||
*/
|
||||
public int keysizeDES = 0;
|
||||
/**
|
||||
* AES
|
||||
*/
|
||||
public int keysizeAES = 128;
|
||||
|
||||
public static EncryptUtil me;
|
||||
|
||||
private EncryptUtil() {
|
||||
//单例
|
||||
}
|
||||
|
||||
//双重锁
|
||||
public static EncryptUtil getInstance() {
|
||||
if (me == null) {
|
||||
synchronized (EncryptUtil.class) {
|
||||
if (me == null) {
|
||||
me = new EncryptUtil();
|
||||
}
|
||||
}
|
||||
}
|
||||
return me;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用MessageDigest进行单向加密(无密码)
|
||||
*
|
||||
* @param res 被加密的文本
|
||||
* @param algorithm 加密算法名称
|
||||
* @return
|
||||
*/
|
||||
private String messageDigest(String res, String algorithm) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance(algorithm);
|
||||
byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
|
||||
return base64(md.digest(resBytes));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用KeyGenerator进行单向/双向加密(可设密码)
|
||||
*
|
||||
* @param res 被加密的原文
|
||||
* @param algorithm 加密使用的算法名称
|
||||
* @param key 加密使用的秘钥
|
||||
* @return
|
||||
*/
|
||||
private String keyGeneratorMac(String res, String algorithm, String key) {
|
||||
try {
|
||||
SecretKey sk = null;
|
||||
if (key == null) {
|
||||
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
|
||||
sk = kg.generateKey();
|
||||
} else {
|
||||
byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
|
||||
sk = new SecretKeySpec(keyBytes, algorithm);
|
||||
}
|
||||
Mac mac = Mac.getInstance(algorithm);
|
||||
mac.init(sk);
|
||||
byte[] result = mac.doFinal(res.getBytes());
|
||||
return base64(result);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错
|
||||
*
|
||||
* @param res 加密的原文
|
||||
* @param algorithm 加密使用的算法名称
|
||||
* @param key 加密的秘钥
|
||||
* @param keysize
|
||||
* @param isEncode
|
||||
* @return
|
||||
*/
|
||||
private String keyGeneratorES(String res, String algorithm, String key, int keysize, boolean isEncode) {
|
||||
try {
|
||||
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
|
||||
if (keysize == 0) {
|
||||
byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
|
||||
kg.init(new SecureRandom(keyBytes));
|
||||
} else if (key == null) {
|
||||
kg.init(keysize);
|
||||
} else {
|
||||
byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
|
||||
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
|
||||
secureRandom.setSeed(keyBytes);
|
||||
kg.init(keysize, secureRandom);
|
||||
}
|
||||
SecretKey sk = kg.generateKey();
|
||||
SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
|
||||
Cipher cipher = Cipher.getInstance(algorithm);
|
||||
if (isEncode) {
|
||||
cipher.init(Cipher.ENCRYPT_MODE, sks);
|
||||
byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
|
||||
return parseByte2HexStr(cipher.doFinal(resBytes));
|
||||
} else {
|
||||
cipher.init(Cipher.DECRYPT_MODE, sks);
|
||||
return new String(cipher.doFinal(parseHexStr2Byte(res)));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String base64(byte[] res) {
|
||||
return new String(Base64.encode(res));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将二进制转换成16进制
|
||||
*/
|
||||
public static String parseByte2HexStr(byte buf[]) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0; i < buf.length; i++) {
|
||||
String hex = Integer.toHexString(buf[i] & 0xFF);
|
||||
if (hex.length() == 1) {
|
||||
hex = '0' + hex;
|
||||
}
|
||||
sb.append(hex.toUpperCase());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将16进制转换为二进制
|
||||
*/
|
||||
public static byte[] parseHexStr2Byte(String hexStr) {
|
||||
if (hexStr.length() < 1) {
|
||||
return null;
|
||||
}
|
||||
byte[] result = new byte[hexStr.length() / 2];
|
||||
for (int i = 0; i < hexStr.length() / 2; i++) {
|
||||
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
|
||||
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
|
||||
result[i] = (byte) (high * 16 + low);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* md5加密算法进行加密(不可逆)
|
||||
*
|
||||
* @param res 需要加密的原文
|
||||
* @return
|
||||
*/
|
||||
public String MD5(String res) {
|
||||
return messageDigest(res, MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* md5加密算法进行加密(不可逆)
|
||||
*
|
||||
* @param res 需要加密的原文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String MD5(String res, String key) {
|
||||
return keyGeneratorMac(res, HmacMD5, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用SHA1加密算法进行加密(不可逆)
|
||||
*
|
||||
* @param res 需要加密的原文
|
||||
* @return
|
||||
*/
|
||||
public String SHA1(String res) {
|
||||
return messageDigest(res, SHA1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用SHA1加密算法进行加密(不可逆)
|
||||
*
|
||||
* @param res 需要加密的原文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String SHA1(String res, String key) {
|
||||
return keyGeneratorMac(res, HmacSHA1, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用DES加密算法进行加密(可逆)
|
||||
*
|
||||
* @param res 需要加密的原文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String DESencode(String res, String key) {
|
||||
return keyGeneratorES(res, DES, key, keysizeDES, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对使用DES加密算法的密文进行解密(可逆)
|
||||
*
|
||||
* @param res 需要解密的密文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String DESdecode(String res, String key) {
|
||||
return keyGeneratorES(res, DES, key, keysizeDES, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密算法经行加密(可逆)
|
||||
*
|
||||
* @param res 需要加密的密文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String AESencode(String res, String key) {
|
||||
return keyGeneratorES(res, AES, key, keysizeAES, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对使用AES加密算法的密文进行解密
|
||||
*
|
||||
* @param res 需要解密的密文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String AESdecode(String res, String key) {
|
||||
return keyGeneratorES(res, AES, key, keysizeAES, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用异或进行加密
|
||||
*
|
||||
* @param res 需要加密的密文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String XORencode(String res, String key) {
|
||||
byte[] bs = res.getBytes();
|
||||
for (int i = 0; i < bs.length; i++) {
|
||||
bs[i] = (byte) ((bs[i]) ^ key.hashCode());
|
||||
}
|
||||
return parseByte2HexStr(bs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用异或进行解密
|
||||
*
|
||||
* @param res 需要解密的密文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public String XORdecode(String res, String key) {
|
||||
byte[] bs = parseHexStr2Byte(res);
|
||||
for (int i = 0; i < bs.length; i++) {
|
||||
bs[i] = (byte) ((bs[i]) ^ key.hashCode());
|
||||
}
|
||||
return new String(bs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接使用异或(第一调用加密,第二次调用解密)
|
||||
*
|
||||
* @param res 密文
|
||||
* @param key 秘钥
|
||||
* @return
|
||||
*/
|
||||
public int XOR(int res, String key) {
|
||||
return res ^ key.hashCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用Base64进行加密
|
||||
*
|
||||
* @param res 密文
|
||||
* @return
|
||||
*/
|
||||
public String Base64Encode(String res) {
|
||||
return String.valueOf(Base64.encode(res.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用Base64进行解密
|
||||
*
|
||||
* @param res
|
||||
* @return
|
||||
*/
|
||||
public String Base64Decode(String res) {
|
||||
return new String(Base64.decode(res));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpClient {
|
||||
|
||||
|
||||
//连接超时时间
|
||||
private static final int CONNECTION_TIME_OUT = 30000;
|
||||
|
||||
//读取超时时间
|
||||
private static final int READ_TIME_OUT = 30000;
|
||||
|
||||
/**
|
||||
* post方法接口
|
||||
* @param targetUrl---访问的接口网址
|
||||
* @param map----携带的参数
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,Object> postMethod(String targetUrl, Map<String,Object> map){
|
||||
//兑换带ticket的url
|
||||
String urlPath = targetUrl;
|
||||
// 发送请求
|
||||
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
|
||||
JSONArray jsonArray1 = new JSONArray();
|
||||
Map<String, Object> map2 = HttpClient.getCasUtils(jsonObject, jsonArray1, "");
|
||||
RestTemplate restTemplate = (RestTemplate) map2.get("restTemplate");
|
||||
HttpEntity<String> httprequest = (HttpEntity<String>) map2.get("httprequest");
|
||||
String response = restTemplate.postForObject(urlPath, httprequest, String.class);
|
||||
JSONObject jsonObject1 = JSON.parseObject(response);
|
||||
Map<String, Object> resultMap = JSONObject.toJavaObject(jsonObject1, Map.class);
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* get方法
|
||||
* @param targetUrl---目标地址
|
||||
* @param itemMap----传入参数
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,Object> getMethod(String targetUrl,Map<String,Object> itemMap){
|
||||
String url = targetUrl;
|
||||
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(itemMap));
|
||||
JSONArray jsonArray = new JSONArray();
|
||||
Map<String, Object> map = HttpClient.getCasUtils(jsonObject,jsonArray,"");
|
||||
RestTemplate restTemplate = (RestTemplate) map.get("restTemplate");
|
||||
String response=restTemplate.getForEntity(url,String.class).getBody();
|
||||
JSONObject result = JSON.parseObject(response);
|
||||
Map<String, Object> resultMap = JSONObject.toJavaObject(result, Map.class);
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static Map<String,Object> getCasUtils(JSONObject jsonObject, JSONArray jsonArray, String str){
|
||||
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(CONNECTION_TIME_OUT);
|
||||
requestFactory.setReadTimeout(READ_TIME_OUT);
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
// 参数
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
|
||||
headers.setContentType(type);
|
||||
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
|
||||
HttpEntity<String> httprequest= null;
|
||||
if (jsonObject.isEmpty()&&!jsonArray.isEmpty()) {
|
||||
httprequest = new HttpEntity<String>(jsonArray.toJSONString(), headers);
|
||||
} else if (jsonArray.isEmpty() && !jsonObject.isEmpty()) {
|
||||
httprequest = new HttpEntity<String>(jsonObject.toJSONString(), headers);
|
||||
} else {
|
||||
httprequest = new HttpEntity<String>(str, headers);
|
||||
}
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("restTemplate", restTemplate);
|
||||
map.put("httprequest", httprequest);
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
|
||||
public class JudgeException {
|
||||
|
||||
public static void isNull(Object o, String msg) {
|
||||
if (o == null) {
|
||||
throw new ServiceException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class ListUtil {
|
||||
|
||||
public static Map<String,Object> getValue(String value, List<Map<String,Object>> list,String key) {
|
||||
Optional<Map<String, Object>> objectMap = list
|
||||
.stream()
|
||||
.filter(r -> (Integer) r.get(key) == Integer.parseInt(value))
|
||||
.findFirst();
|
||||
if (objectMap.isPresent()) {
|
||||
return objectMap.get();
|
||||
} else {
|
||||
throw new ServiceException("key值不存在");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import org.springframework.util.DigestUtils;
|
||||
|
||||
public class MD5Util {
|
||||
|
||||
public static String setMd5(String password){
|
||||
return DigestUtils.md5DigestAsHex(password.getBytes());
|
||||
}
|
||||
|
||||
public static boolean isEqual(String password, String md5) {
|
||||
String str = DigestUtils.md5DigestAsHex(password.getBytes());
|
||||
if (md5.equals(str)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import javax.mail.Authenticator;
|
||||
import javax.mail.PasswordAuthentication;
|
||||
|
||||
public class MailAuthenticator extends Authenticator{
|
||||
String userName=null;
|
||||
String password=null;
|
||||
|
||||
public MailAuthenticator(){
|
||||
}
|
||||
public MailAuthenticator(String username, String password) {
|
||||
this.userName = username;
|
||||
this.password = password;
|
||||
}
|
||||
@Override
|
||||
protected PasswordAuthentication getPasswordAuthentication(){
|
||||
return new PasswordAuthentication(userName, password);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MailBean {
|
||||
// 发送邮件的服务器的IP和端口
|
||||
private String mailServerHost;
|
||||
private String mailServerPort = "25";
|
||||
// 邮件发送者的地址
|
||||
private String fromAddress;
|
||||
// 邮件接收者的地址
|
||||
private List<String> toAddress;
|
||||
// 登陆邮件发送服务器的用户名和密码
|
||||
private String userName;
|
||||
private String password;
|
||||
// 是否需要身份验证
|
||||
private boolean validate = false;
|
||||
// 邮件主题
|
||||
private String subject;
|
||||
// 邮件的文本内容
|
||||
private String content;
|
||||
// 邮件附件的文件名
|
||||
private List<String> attachFileNames;
|
||||
/**
|
||||
* 获得邮件会话属性
|
||||
*/
|
||||
|
||||
public Properties getProperties(){
|
||||
Properties p = new Properties();
|
||||
p.put("mail.smtp.host", this.mailServerHost);
|
||||
p.put("mail.smtp.port", this.mailServerPort);
|
||||
p.put("mail.smtp.auth", validate ? "true" : "false");
|
||||
p.put("mail.mime.address.strict", "false");
|
||||
return p;
|
||||
}
|
||||
public String getMailServerHost() {
|
||||
return mailServerHost;
|
||||
}
|
||||
public void setMailServerHost(String mailServerHost) {
|
||||
this.mailServerHost = mailServerHost;
|
||||
}
|
||||
public String getMailServerPort() {
|
||||
return mailServerPort;
|
||||
}
|
||||
public void setMailServerPort(String mailServerPort) {
|
||||
this.mailServerPort = mailServerPort;
|
||||
}
|
||||
public String getFromAddress() {
|
||||
return fromAddress;
|
||||
}
|
||||
public void setFromAddress(String fromAddress) {
|
||||
this.fromAddress = fromAddress;
|
||||
}
|
||||
|
||||
public List<String> getToAddress() {
|
||||
return toAddress;
|
||||
}
|
||||
public void setToAddress(List<String> toAddress) {
|
||||
this.toAddress = toAddress;
|
||||
}
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public boolean isValidate() {
|
||||
return validate;
|
||||
}
|
||||
public void setValidate(boolean validate) {
|
||||
this.validate = validate;
|
||||
}
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
public List<String> getAttachFileNames() {
|
||||
return attachFileNames;
|
||||
}
|
||||
public void setAttachFileNames(List<String> attachFileNames) {
|
||||
this.attachFileNames = attachFileNames;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
|
||||
import javax.activation.DataHandler;
|
||||
import javax.activation.FileDataSource;
|
||||
import javax.mail.*;
|
||||
import javax.mail.internet.*;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
public class MailOperate {
|
||||
/**
|
||||
* 以文本格式发送邮件
|
||||
* @param mailInfo 待发送的邮件的信息
|
||||
*/
|
||||
public boolean sendTextMail(MailBean mailInfo) {
|
||||
// 判断是否需要身份认证
|
||||
MailAuthenticator authenticator = null;
|
||||
Properties pro = mailInfo.getProperties();
|
||||
if (mailInfo.isValidate()) {
|
||||
// 如果需要身份认证,则创建一个密码验证器
|
||||
authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
|
||||
}
|
||||
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
|
||||
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
|
||||
try {
|
||||
// 根据session创建一个邮件消息
|
||||
Message mailMessage = new MimeMessage(sendMailSession);
|
||||
// 创建邮件发送者地址
|
||||
Address from = new InternetAddress(mailInfo.getFromAddress());
|
||||
// 设置邮件消息的发送者
|
||||
mailMessage.setFrom(from);
|
||||
// 创建邮件的接收者地址,并设置到邮件消息中
|
||||
List<String> toAddress=null;
|
||||
if(mailInfo.getToAddress().size()>1){
|
||||
toAddress=mailInfo.getToAddress();
|
||||
Address[] address =new InternetAddress[toAddress.size()];
|
||||
for (int i = 0; i < toAddress.size(); i++) {
|
||||
address[i]=new InternetAddress(toAddress.get(i));
|
||||
}
|
||||
mailMessage.setRecipients(Message.RecipientType.TO,address);
|
||||
}else{
|
||||
toAddress=mailInfo.getToAddress();
|
||||
Address to = new InternetAddress(toAddress.get(0));
|
||||
// Message.RecipientType.TO属性表示接收者的类型为TO
|
||||
mailMessage.setRecipient(Message.RecipientType.TO,to);
|
||||
}
|
||||
// 设置邮件消息的主题
|
||||
mailMessage.setSubject(mailInfo.getSubject());
|
||||
// 设置邮件消息发送的时间
|
||||
mailMessage.setSentDate(new Date());
|
||||
// 设置邮件消息的主要内容
|
||||
String mailContent = mailInfo.getContent();
|
||||
mailMessage.setText(mailContent);
|
||||
// 发送邮件
|
||||
Transport.send(mailMessage);
|
||||
return true;
|
||||
} catch (MessagingException ex) {
|
||||
// ex.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
// return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 以HTML格式发送邮件
|
||||
* @param mailInfo 待发送的邮件信息
|
||||
* @throws UnsupportedEncodingException
|
||||
*/
|
||||
public static boolean sendHtmlMail(MailBean mailInfo) throws UnsupportedEncodingException{
|
||||
// 判断是否需要身份认证
|
||||
MailAuthenticator authenticator = null;
|
||||
Properties pro = mailInfo.getProperties();
|
||||
//如果需要身份认证,则创建一个密码验证器
|
||||
if (mailInfo.isValidate()) {
|
||||
authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
|
||||
}
|
||||
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
|
||||
Session sendMailSession = Session.getInstance(pro,authenticator);
|
||||
|
||||
try {
|
||||
// 根据session创建一个邮件消息
|
||||
Message mailMessage = new MimeMessage(sendMailSession);
|
||||
// 创建邮件发送者地址
|
||||
Address from = new InternetAddress(mailInfo.getFromAddress());
|
||||
// 设置邮件消息的发送者
|
||||
mailMessage.setFrom(from);
|
||||
// 创建邮件的接收者地址,并设置到邮件消息中
|
||||
List<String> toAddress=null;
|
||||
if(mailInfo.getToAddress().size()>1){
|
||||
toAddress=mailInfo.getToAddress();
|
||||
Address[] address =new InternetAddress[toAddress.size()];
|
||||
for (int i = 0; i < toAddress.size(); i++) {
|
||||
address[i]=new InternetAddress(toAddress.get(i));
|
||||
}
|
||||
mailMessage.setRecipients(Message.RecipientType.TO,address);
|
||||
}else{
|
||||
toAddress=mailInfo.getToAddress();
|
||||
Address to = new InternetAddress(toAddress.get(0));
|
||||
// Message.RecipientType.TO属性表示接收者的类型为TO
|
||||
mailMessage.setRecipient(Message.RecipientType.TO,to);
|
||||
}
|
||||
|
||||
// 设置邮件消息的主题
|
||||
mailMessage.setSubject(mailInfo.getSubject());
|
||||
// 设置邮件消息发送的时间
|
||||
mailMessage.setSentDate(new Date());
|
||||
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
|
||||
Multipart mainPart = new MimeMultipart();
|
||||
// 创建一个包含HTML内容的MimeBodyPart
|
||||
BodyPart html = new MimeBodyPart();
|
||||
// 设置HTML内容
|
||||
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
|
||||
mainPart.addBodyPart(html);
|
||||
if(mailInfo.getAttachFileNames()!=null){
|
||||
List<String> attachFileNames = mailInfo.getAttachFileNames();
|
||||
for (String path : attachFileNames) {
|
||||
html=new MimeBodyPart();
|
||||
FileDataSource fds=new FileDataSource(path); //得到数据源
|
||||
html.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
|
||||
//此处是为了解决附件中文名乱码的问题
|
||||
String fileName= MimeUtility.encodeText(fds.getName());
|
||||
html.setFileName(fileName); //得到文件名同样至入BodyPart
|
||||
mainPart.addBodyPart(html);
|
||||
}
|
||||
}
|
||||
|
||||
// 将MiniMultipart对象设置为邮件内容
|
||||
mailMessage.setContent(mainPart);
|
||||
// 发送邮件
|
||||
Transport.send(mailMessage);
|
||||
return true;
|
||||
} catch (MessagingException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
|
||||
public class MyPageHelper {
|
||||
|
||||
public static void start(WebPageInfo webPageInfo) {
|
||||
if (WebPageInfo.hasSort(webPageInfo)) {
|
||||
PageHelper.startPage(webPageInfo.getPageNum(), webPageInfo.getPageSize(), webPageInfo.getSortSql());
|
||||
} else {
|
||||
PageHelper.startPage(webPageInfo.getPageNum(), webPageInfo.getPageSize());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.module.data.annotation.DataIgnore;
|
||||
import com.hcframe.base.module.data.exception.BaseMapperException;
|
||||
import com.hcframe.base.module.data.module.DataMap;
|
||||
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ObjectUtil {
|
||||
|
||||
private static final String SERIAL_VERSION_UID = "serialVersionUID";
|
||||
private static final String STRING = "class java.lang.String";
|
||||
private static final String INTEGER = "class java.lang.Integer";
|
||||
private static final String LONG = "class java.lang.LONG";
|
||||
|
||||
public static Map<String, Object> objToMap(Object obj) {
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
Class<?> clazz = obj.getClass();
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
String fieldName = field.getName();
|
||||
try {
|
||||
if (!org.springframework.util.StringUtils.isEmpty(field.get(obj)) && !fieldName.equals(SERIAL_VERSION_UID)) {
|
||||
Object value = field.get(obj);
|
||||
map.put(fieldName, value);
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public static <T> void objToSqlMap(Object obj, DataMap<T> dataMap) {
|
||||
Class<?> clazz = obj.getClass();
|
||||
Map<String, Object> map = new HashMap<String, Object>(clazz.getDeclaredFields().length);
|
||||
List<String> fieldList = new ArrayList<>();
|
||||
if (clazz.getAnnotation(Table.class) != null) {
|
||||
Table table = clazz.getAnnotation(Table.class);
|
||||
dataMap = dataMap.toBuilder().tableName(table.name()).build();
|
||||
}
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
String fieldName = field.getName();
|
||||
if (field.getAnnotation(Id.class) != null) {
|
||||
dataMap = dataMap.toBuilder().pkName(StringUtils.toUnderScoreUpperCase(fieldName)).build();
|
||||
}
|
||||
try {
|
||||
if (!fieldName.equals(SERIAL_VERSION_UID)) {
|
||||
if (!org.springframework.util.StringUtils.isEmpty(field.get(obj))) {
|
||||
Object value = field.get(obj);
|
||||
map.put(StringUtils.toUnderScoreUpperCase(fieldName), value);
|
||||
}
|
||||
if (field.getAnnotation(DataIgnore.class) == null) {
|
||||
fieldList.add(StringUtils.toUnderScoreUpperCase(fieldName));
|
||||
}
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
dataMap.toBuilder().data(map).fieldList(fieldList).build();
|
||||
}
|
||||
|
||||
public static <T> void objToSqlMap(Object obj, DataMap.DataMapBuilder<T> dataMap) {
|
||||
Class<?> clazz = obj.getClass();
|
||||
Map<String, Object> map = new HashMap<String, Object>(clazz.getDeclaredFields().length);
|
||||
List<String> fieldList = new ArrayList<>();
|
||||
if (clazz.getAnnotation(Table.class) != null) {
|
||||
Table table = clazz.getAnnotation(Table.class);
|
||||
if (StringUtils.isEmpty(table.name())) {
|
||||
throw new BaseMapperException("请检查实体类是否添加注解@Table,并且name中是否正确设置了表名");
|
||||
}
|
||||
dataMap = dataMap.tableName(table.name());
|
||||
}
|
||||
for (Field field : clazz.getDeclaredFields()) {
|
||||
field.setAccessible(true);
|
||||
String fieldName = field.getName();
|
||||
if (field.getAnnotation(Id.class) != null) {
|
||||
dataMap = dataMap.pkName(StringUtils.toUnderScoreUpperCase(fieldName));
|
||||
}
|
||||
try {
|
||||
if (!fieldName.equals(SERIAL_VERSION_UID)) {
|
||||
if (!org.springframework.util.StringUtils.isEmpty(field.get(obj))) {
|
||||
Object value = field.get(obj);
|
||||
map.put(StringUtils.toUnderScoreUpperCase(fieldName), value);
|
||||
}
|
||||
if (field.getAnnotation(DataIgnore.class) == null) {
|
||||
fieldList.add(StringUtils.toUnderScoreUpperCase(fieldName));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
dataMap.data(map).fieldList(fieldList);
|
||||
}
|
||||
|
||||
public static void setField(Object obj, String key, Object value) {
|
||||
Class<?> clazz = obj.getClass();
|
||||
try {
|
||||
Field field = clazz.getDeclaredField(key);
|
||||
field.setAccessible(true);
|
||||
String str = field.getGenericType().toString();
|
||||
if (STRING.equals(str)) {
|
||||
value = value.toString();
|
||||
}
|
||||
if (INTEGER.equals(str)) {
|
||||
value = Integer.valueOf(value.toString());
|
||||
}
|
||||
if (LONG.equals(str)) {
|
||||
value = Long.valueOf(value.toString());
|
||||
}
|
||||
try {
|
||||
field.set(obj, value);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new ServiceException("字段类型不匹配", e);
|
||||
}
|
||||
} catch (NoSuchFieldException e) {
|
||||
throw new ServiceException("无法找到相应的字段", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomUtil {
|
||||
|
||||
|
||||
public static String getrandom() {
|
||||
StringBuilder code = new StringBuilder();
|
||||
Random random = new Random();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
int r = random.nextInt(10);
|
||||
code.append(r);
|
||||
}
|
||||
return code.toString();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.hcframe.base.common.config.FrameConfig;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
|
||||
/**
|
||||
* Redis工具类
|
||||
*/
|
||||
|
||||
@Component
|
||||
public final class RedisUtil {
|
||||
|
||||
// url
|
||||
public static boolean isUseful;
|
||||
|
||||
// 通过yml文件获取host
|
||||
@Autowired
|
||||
public void setHost(FrameConfig config) {
|
||||
RedisUtil.isUseful = config.getIsRedisLogin();
|
||||
}
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
/**
|
||||
* 指定缓存失效时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean expire(String key, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.expire(key, time, TimeUnit.SECONDS);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据key 获取过期时间
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @return 时间(秒) 返回0代表为永久有效
|
||||
*/
|
||||
public long getExpire(String key) {
|
||||
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断key是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hasKey(String key) {
|
||||
try {
|
||||
return redisTemplate.hasKey(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存
|
||||
*
|
||||
* @param key 可以传一个值 或多个
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void del(String... key) {
|
||||
if (key != null && key.length > 0) {
|
||||
if (key.length == 1) {
|
||||
redisTemplate.delete(key[0]);
|
||||
} else {
|
||||
redisTemplate.delete(CollectionUtils.arrayToList(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
// ============================String=============================
|
||||
|
||||
/**
|
||||
* 普通缓存获取
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object get(String key) {
|
||||
return key == null ? null : redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean set(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 普通缓存放入并设置时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
|
||||
* @return true成功 false 失败
|
||||
*/
|
||||
public boolean set(String key, Object value, long time) {
|
||||
try {
|
||||
if (time > 0) {
|
||||
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
|
||||
} else {
|
||||
set(key, value);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递增
|
||||
*
|
||||
* @param key 键
|
||||
* @param delta 要增加几(大于0)
|
||||
* @return
|
||||
*/
|
||||
public long incr(String key, long delta) {
|
||||
if (delta < 0) {
|
||||
throw new RuntimeException("递增因子必须大于0");
|
||||
}
|
||||
return redisTemplate.opsForValue().increment(key, delta);
|
||||
}
|
||||
|
||||
/**
|
||||
* 递减
|
||||
*
|
||||
* @param key 键
|
||||
* @param delta 要减少几(小于0)
|
||||
* @return
|
||||
*/
|
||||
public long decr(String key, long delta) {
|
||||
if (delta < 0) {
|
||||
throw new RuntimeException("递减因子必须大于0");
|
||||
}
|
||||
return redisTemplate.opsForValue().increment(key, -delta);
|
||||
}
|
||||
// ================================Map=================================
|
||||
|
||||
/**
|
||||
* HashGet
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return 值
|
||||
*/
|
||||
public Object hget(String key, String item) {
|
||||
return redisTemplate.opsForHash().get(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取hashKey对应的所有键值
|
||||
*
|
||||
* @param key 键
|
||||
* @return 对应的多个键值
|
||||
*/
|
||||
public Map<Object, Object> hmget(String key) {
|
||||
return redisTemplate.opsForHash().entries(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* HashSet
|
||||
*
|
||||
* @param key 键
|
||||
* @param map 对应多个键值
|
||||
* @return true 成功 false 失败
|
||||
*/
|
||||
public boolean hmset(String key, Map<String, Object> map) {
|
||||
try {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HashSet 并设置时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param map 对应多个键值
|
||||
* @param time 时间(秒)
|
||||
* @return true成功 false失败
|
||||
*/
|
||||
public boolean hmset(String key, Map<String, Object> map, long time) {
|
||||
try {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key, String item, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向一张hash表中放入数据,如果不存在将创建
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param value 值
|
||||
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
|
||||
* @return true 成功 false失败
|
||||
*/
|
||||
public boolean hset(String key, String item, Object value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForHash().put(key, item, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除hash表中的值
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 可以使多个 不能为null
|
||||
*/
|
||||
public void hdel(String key, Object... item) {
|
||||
redisTemplate.opsForHash().delete(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断hash表中是否有该项的值
|
||||
*
|
||||
* @param key 键 不能为null
|
||||
* @param item 项 不能为null
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean hHasKey(String key, String item) {
|
||||
return redisTemplate.opsForHash().hasKey(key, item);
|
||||
}
|
||||
|
||||
/**
|
||||
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param by 要增加几(大于0)
|
||||
* @return
|
||||
*/
|
||||
public double hincr(String key, String item, double by) {
|
||||
return redisTemplate.opsForHash().increment(key, item, by);
|
||||
}
|
||||
|
||||
/**
|
||||
* hash递减
|
||||
*
|
||||
* @param key 键
|
||||
* @param item 项
|
||||
* @param by 要减少记(小于0)
|
||||
* @return
|
||||
*/
|
||||
public double hdecr(String key, String item, double by) {
|
||||
return redisTemplate.opsForHash().increment(key, item, -by);
|
||||
}
|
||||
// ============================set=============================
|
||||
|
||||
/**
|
||||
* 根据key获取Set中的所有值
|
||||
*
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public Set<Object> sGet(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().members(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据value从一个set中查询,是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return true 存在 false不存在
|
||||
*/
|
||||
public boolean sHasKey(String key, Object value) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().isMember(key, value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据放入set缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSet(String key, Object... values) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().add(key, values);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将set数据放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param time 时间(秒)
|
||||
* @param values 值 可以是多个
|
||||
* @return 成功个数
|
||||
*/
|
||||
public long sSetAndTime(String key, long time, Object... values) {
|
||||
try {
|
||||
Long count = redisTemplate.opsForSet().add(key, values);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取set缓存的长度
|
||||
*
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public long sGetSetSize(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForSet().size(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除值为value的
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值 可以是多个
|
||||
* @return 移除的个数
|
||||
*/
|
||||
public long setRemove(String key, Object... values) {
|
||||
try {
|
||||
Long count = redisTemplate.opsForSet().remove(key, values);
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
// ===============================list=================================
|
||||
|
||||
/**
|
||||
* 获取list缓存的内容
|
||||
*
|
||||
* @param key 键
|
||||
* @param start 开始
|
||||
* @param end 结束 0 到 -1代表所有值
|
||||
* @return
|
||||
*/
|
||||
public List<Object> lGet(String key, long start, long end) {
|
||||
try {
|
||||
return redisTemplate.opsForList().range(key, start, end);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取list缓存的长度
|
||||
*
|
||||
* @param key 键
|
||||
* @return
|
||||
*/
|
||||
public long lGetListSize(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForList().size(key);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过索引 获取list中的值
|
||||
*
|
||||
* @param key 键
|
||||
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
|
||||
* @return
|
||||
*/
|
||||
public Object lGetIndex(String key, long index) {
|
||||
try {
|
||||
return redisTemplate.opsForList().index(key, index);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, Object value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPush(key, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, List<Object> value) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPushAll(key, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将list放入缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param time 时间(秒)
|
||||
* @return
|
||||
*/
|
||||
public boolean lSet(String key, List<Object> value, long time) {
|
||||
try {
|
||||
redisTemplate.opsForList().rightPushAll(key, value);
|
||||
if (time > 0) {
|
||||
expire(key, time);
|
||||
}
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据索引修改list中的某条数据
|
||||
*
|
||||
* @param key 键
|
||||
* @param index 索引
|
||||
* @param value 值
|
||||
* @return
|
||||
*/
|
||||
public boolean lUpdateIndex(String key, long index, Object value) {
|
||||
try {
|
||||
redisTemplate.opsForList().set(key, index, value);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除N个值为value
|
||||
*
|
||||
* @param key 键
|
||||
* @param count 移除多少个
|
||||
* @param value 值
|
||||
* @return 移除的个数
|
||||
*/
|
||||
public long lRemove(String key, long count, Object value) {
|
||||
try {
|
||||
return redisTemplate.opsForList().remove(key, count, value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class RegexUtil {
|
||||
|
||||
public static boolean isChinese(String str) {
|
||||
String pattern = "^([\\u4E00-\\u9FA5])*$";
|
||||
return Pattern.matches(pattern, str);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringContextUtil implements ApplicationContextAware{
|
||||
private static ApplicationContext applicationContext;
|
||||
//获取上下文
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
//设置上下文
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringContextUtil.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
//通过名字获取上下文中的bean
|
||||
public static Object getBean(String name){
|
||||
return applicationContext.getBean(name);
|
||||
}
|
||||
//通过类型获取上下文中的bean
|
||||
public static Object getBean(Class<?> requiredType){
|
||||
return applicationContext.getBean(requiredType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
|
||||
/**
|
||||
* 字符串工具类
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class StringUtils extends org.apache.commons.lang3.StringUtils {
|
||||
/**
|
||||
* 空字符串
|
||||
*/
|
||||
private static final String NULLSTR = "";
|
||||
|
||||
/**
|
||||
* 下划线
|
||||
*/
|
||||
private static final char SEPARATOR = '_';
|
||||
|
||||
/**
|
||||
* 获取参数不为空值
|
||||
*
|
||||
* @param value defaultValue 要判断的value
|
||||
* @return value 返回值
|
||||
*/
|
||||
public static <T> T nvl(T value, T defaultValue) {
|
||||
return value != null ? value : defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Collection是否为空, 包含List,Set,Queue
|
||||
*
|
||||
* @param coll 要判断的Collection
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Collection<?> coll) {
|
||||
return isNull(coll) || coll.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Collection是否非空,包含List,Set,Queue
|
||||
*
|
||||
* @param coll 要判断的Collection
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotEmpty(Collection<?> coll) {
|
||||
return !isEmpty(coll);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象数组是否为空
|
||||
*
|
||||
* @param objects 要判断的对象数组
|
||||
* * @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Object[] objects) {
|
||||
return isNull(objects) || (objects.length == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象数组是否非空
|
||||
*
|
||||
* @param objects 要判断的对象数组
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotEmpty(Object[] objects) {
|
||||
return !isEmpty(objects);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Map是否为空
|
||||
*
|
||||
* @param map 要判断的Map
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(Map<?, ?> map) {
|
||||
return isNull(map) || map.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个Map是否为空
|
||||
*
|
||||
* @param map 要判断的Map
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotEmpty(Map<?, ?> map) {
|
||||
return !isEmpty(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个字符串是否为空串
|
||||
*
|
||||
* @param str String
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isEmpty(String str) {
|
||||
return isNull(str) || NULLSTR.equals(str.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个字符串是否为非空串
|
||||
*
|
||||
* @param str String
|
||||
* @return true:非空串 false:空串
|
||||
*/
|
||||
public static boolean isNotEmpty(String str) {
|
||||
return !isEmpty(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否为空
|
||||
*
|
||||
* @param object Object
|
||||
* @return true:为空 false:非空
|
||||
*/
|
||||
public static boolean isNull(Object object) {
|
||||
return object == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否非空
|
||||
*
|
||||
* @param object Object
|
||||
* @return true:非空 false:空
|
||||
*/
|
||||
public static boolean isNotNull(Object object) {
|
||||
return !isNull(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* * 判断一个对象是否是数组类型(Java基本型别的数组)
|
||||
*
|
||||
* @param object 对象
|
||||
* @return true:是数组 false:不是数组
|
||||
*/
|
||||
public static boolean isArray(Object object) {
|
||||
return isNotNull(object) && object.getClass().isArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* 去空格
|
||||
*/
|
||||
public static String trim(String str) {
|
||||
return (str == null ? "" : str.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param start 开始
|
||||
* @return 结果
|
||||
*/
|
||||
public static String substring(final String str, int start) {
|
||||
if (str == null) {
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
if (start < 0) {
|
||||
start = str.length() + start;
|
||||
}
|
||||
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
if (start > str.length()) {
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
return str.substring(start);
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param start 开始
|
||||
* @param end 结束
|
||||
* @return 结果
|
||||
*/
|
||||
public static String substring(final String str, int start, int end) {
|
||||
if (str == null) {
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
if (end < 0) {
|
||||
end = str.length() + end;
|
||||
}
|
||||
if (start < 0) {
|
||||
start = str.length() + start;
|
||||
}
|
||||
|
||||
if (end > str.length()) {
|
||||
end = str.length();
|
||||
}
|
||||
|
||||
if (start > end) {
|
||||
return NULLSTR;
|
||||
}
|
||||
|
||||
if (start < 0) {
|
||||
start = 0;
|
||||
}
|
||||
if (end < 0) {
|
||||
end = 0;
|
||||
}
|
||||
|
||||
return str.substring(start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转set
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param sep 分隔符
|
||||
* @return set集合
|
||||
*/
|
||||
public static final Set<String> str2Set(String str, String sep) {
|
||||
return new HashSet<String>(str2List(str, sep, true, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转list
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param sep 分隔符
|
||||
* @param filterBlank 过滤纯空白
|
||||
* @param trim 去掉首尾空白
|
||||
* @return list集合
|
||||
*/
|
||||
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
|
||||
List<String> list = new ArrayList<String>();
|
||||
if (StringUtils.isEmpty(str)) {
|
||||
return list;
|
||||
}
|
||||
|
||||
// 过滤空白字符串
|
||||
if (filterBlank && StringUtils.isBlank(str)) {
|
||||
return list;
|
||||
}
|
||||
String[] split = str.split(sep);
|
||||
for (String string : split) {
|
||||
if (filterBlank && StringUtils.isBlank(string)) {
|
||||
continue;
|
||||
}
|
||||
if (trim) {
|
||||
string = string.trim();
|
||||
}
|
||||
list.add(string);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下划线转驼峰命名
|
||||
*/
|
||||
public static String toUnderScoreCase(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// 前置字符是否大写
|
||||
boolean preCharIsUpperCase = true;
|
||||
// 当前字符是否大写
|
||||
boolean curreCharIsUpperCase = true;
|
||||
// 下一字符是否大写
|
||||
boolean nexteCharIsUpperCase = true;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
if (i > 0) {
|
||||
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
|
||||
} else {
|
||||
preCharIsUpperCase = false;
|
||||
}
|
||||
|
||||
curreCharIsUpperCase = Character.isUpperCase(c);
|
||||
|
||||
if (i < (str.length() - 1)) {
|
||||
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
|
||||
}
|
||||
|
||||
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
|
||||
sb.append(SEPARATOR);
|
||||
} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 下划线转驼峰命名
|
||||
*/
|
||||
public static String toUnderScoreUpperCase(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// 前置字符是否大写
|
||||
boolean preCharIsUpperCase = true;
|
||||
// 当前字符是否大写
|
||||
boolean curreCharIsUpperCase = true;
|
||||
// 下一字符是否大写
|
||||
boolean nexteCharIsUpperCase = true;
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
if (i > 0) {
|
||||
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
|
||||
} else {
|
||||
preCharIsUpperCase = false;
|
||||
}
|
||||
|
||||
curreCharIsUpperCase = Character.isUpperCase(c);
|
||||
|
||||
if (i < (str.length() - 1)) {
|
||||
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
|
||||
}
|
||||
|
||||
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
|
||||
sb.append(SEPARATOR);
|
||||
} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return sb.toString().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否包含字符串
|
||||
*
|
||||
* @param str 验证字符串
|
||||
* @param strs 字符串组
|
||||
* @return 包含返回true
|
||||
*/
|
||||
public static boolean inStringIgnoreCase(String str, String... strs) {
|
||||
if (str != null && strs != null) {
|
||||
for (String s : strs) {
|
||||
if (str.equalsIgnoreCase(trim(s))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
|
||||
*
|
||||
* @param name 转换前的下划线大写方式命名的字符串
|
||||
* @return 转换后的驼峰式命名的字符串
|
||||
*/
|
||||
public static String convertToCamelCase(String name) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
// 快速检查
|
||||
if (name == null || name.isEmpty()) {
|
||||
// 没必要转换
|
||||
return "";
|
||||
} else if (!name.contains("_")) {
|
||||
// 不含下划线,仅将首字母大写
|
||||
return name.substring(0, 1).toUpperCase() + name.substring(1);
|
||||
}
|
||||
// 用下划线将原始字符串分割
|
||||
String[] camels = name.split("_");
|
||||
for (String camel : camels) {
|
||||
// 跳过原始字符串中开头、结尾的下换线或双重下划线
|
||||
if (camel.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
// 首字母大写
|
||||
result.append(camel.substring(0, 1).toUpperCase());
|
||||
result.append(camel.substring(1).toLowerCase());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰式命名法 例如:user_name->userName
|
||||
*/
|
||||
public static String toCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
s = s.toLowerCase();
|
||||
StringBuilder sb = new StringBuilder(s.length());
|
||||
boolean upperCase = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
|
||||
if (c == SEPARATOR) {
|
||||
upperCase = true;
|
||||
} else if (upperCase) {
|
||||
sb.append(Character.toUpperCase(c));
|
||||
upperCase = false;
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T cast(Object obj) {
|
||||
return (T) obj;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Long l = 1l;
|
||||
System.out.println(l.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import com.hcframe.base.module.cache.emum.CacheType;
|
||||
import com.hcframe.base.module.cache.impl.TableCache;
|
||||
import com.hcframe.base.module.tableconfig.dao.OsSysTableMapper;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import lombok.val;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class TableNameUtil {
|
||||
|
||||
final
|
||||
OsSysTableMapper osSysTableMapper;
|
||||
|
||||
private final TableCache tableCache;
|
||||
|
||||
public TableNameUtil(OsSysTableMapper osSysTableMapper, TableCache tableCache) {
|
||||
this.osSysTableMapper = osSysTableMapper;
|
||||
this.tableCache = tableCache;
|
||||
}
|
||||
|
||||
public OsSysTable getTableName(String typeName) {
|
||||
// 缓存中读取
|
||||
OsSysTable osSysTable = tableCache.getCacheValue(CacheType.tableCache, typeName, OsSysTable.class);
|
||||
JudgeException.isNull(osSysTable, "输入URL错误");
|
||||
return osSysTable;
|
||||
}
|
||||
|
||||
public OsSysTable getTableAllInfo(String typeName) {
|
||||
// 缓存中读取
|
||||
OsSysTable osSysTable = tableCache.getCacheValue(CacheType.tableCache, typeName, OsSysTable.class);
|
||||
JudgeException.isNull(osSysTable, "输入URL错误");
|
||||
return osSysTable;
|
||||
}
|
||||
|
||||
public Map<String, Object> getBaseTableInfo(String tableNames) {
|
||||
String[] tableNameArr = tableNames.split(",");
|
||||
Map<String, Object> resultMap = new HashMap<>(tableNameArr.length);
|
||||
for (String tableName : tableNameArr) {
|
||||
// 读取缓存
|
||||
val list = tableCache.getCacheValue(CacheType.baseCache, tableName, List.class);
|
||||
resultMap.put(tableName, list);
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* 生成Token的工具类
|
||||
*
|
||||
*/
|
||||
public class TokenProccessor {
|
||||
|
||||
private TokenProccessor(){}
|
||||
|
||||
private static final TokenProccessor instance = new TokenProccessor();
|
||||
|
||||
public static TokenProccessor getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成Token
|
||||
* @return
|
||||
*/
|
||||
public String makeToken() {
|
||||
String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";
|
||||
EncryptUtil encryptUtil = EncryptUtil.getInstance();
|
||||
String str = encryptUtil.MD5(token);
|
||||
str = str.replaceAll("/", "");
|
||||
str = str.replaceAll("\\+", "");
|
||||
str = str.replaceAll("=", "");
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import com.hcframe.base.module.shiro.FtToken;
|
||||
import com.hcframe.base.module.shiro.service.ShiroService;
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class UserInfoUtil<T> {
|
||||
|
||||
@Resource
|
||||
ShiroService shiroService;
|
||||
|
||||
/**
|
||||
* 通过request返回用户信息
|
||||
* @param request request
|
||||
* @return 用户类型
|
||||
*/
|
||||
public T getUserInfoByRequest(HttpServletRequest request) {
|
||||
String token = request.getHeader("X-Access-Token");
|
||||
if (StringUtils.isEmpty(token)) {
|
||||
return null;
|
||||
}
|
||||
FtToken ftToken = shiroService.findByToken(token);
|
||||
Date expireData= ftToken.getExpireTime();
|
||||
Date date = new Date();
|
||||
if (date.getTime() > expireData.getTime()) {
|
||||
return null;
|
||||
}
|
||||
return (T) shiroService.findByUserId(ftToken.getUserId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
* @param <T> 用户实体类泛型
|
||||
* @return 返回结果
|
||||
*/
|
||||
public static <T> T getUserInfo(){
|
||||
return (T)SecurityUtils.getSubject().getPrincipal();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户token
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static String getUserToken(HttpServletRequest request){
|
||||
String token = request.getHeader("X-Access-Token");
|
||||
//如果header中不存在token,则从参数中获取token
|
||||
if (org.apache.commons.lang3.StringUtils.isBlank(token)) {
|
||||
token = request.getParameter("token");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hcframe.base.common.utils;
|
||||
|
||||
import static org.thymeleaf.util.StringUtils.split;
|
||||
|
||||
public class XssClass {
|
||||
|
||||
public static boolean sqlInj(String str){
|
||||
String injStr = "'|and|exec|insert|select|delete|update|"+
|
||||
"count|*|%|chr|mid|master|truncate|char|declare|;|or|+|,|<script>";
|
||||
String[] injStra = split(injStr,"|");
|
||||
for (String s : injStra) {
|
||||
if (str.contains(s)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.hcframe.base.module.auth.constants;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-10
|
||||
* @decription 权限常亮信息
|
||||
*/
|
||||
public class AuthConstants {
|
||||
/**
|
||||
* 平台内系统用户的唯一标志
|
||||
*/
|
||||
public static final String SYS_USER = "SYS_USER";
|
||||
|
||||
/**
|
||||
* 正常状态
|
||||
*/
|
||||
public static final String NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 异常状态
|
||||
*/
|
||||
public static final String EXCEPTION = "1";
|
||||
|
||||
/**
|
||||
* 用户封禁状态
|
||||
*/
|
||||
public static final String USER_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 角色封禁状态
|
||||
*/
|
||||
public static final String ROLE_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 部门正常状态
|
||||
*/
|
||||
public static final String DEPT_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 部门停用状态
|
||||
*/
|
||||
public static final String DEPT_DISABLE = "1";
|
||||
|
||||
/**
|
||||
* 字典正常状态
|
||||
*/
|
||||
public static final String DICT_NORMAL = "0";
|
||||
|
||||
/**
|
||||
* 是否为系统默认(是)
|
||||
*/
|
||||
public static final String YES = "Y";
|
||||
|
||||
/**
|
||||
* 是否菜单外链(是)
|
||||
*/
|
||||
public static final String YES_FRAME = "1";
|
||||
|
||||
/**
|
||||
* 是否菜单外链(否)
|
||||
*/
|
||||
public static final String NO_FRAME = "0";
|
||||
|
||||
/**
|
||||
* 菜单类型(目录)
|
||||
*/
|
||||
public static final String TYPE_DIR = "M";
|
||||
|
||||
/**
|
||||
* 菜单类型(菜单)
|
||||
*/
|
||||
public static final String TYPE_MENU = "C";
|
||||
|
||||
/**
|
||||
* 菜单类型(按钮)
|
||||
*/
|
||||
public static final String TYPE_BUTTON = "F";
|
||||
|
||||
/**
|
||||
* Layout组件标识
|
||||
*/
|
||||
public final static String LAYOUT = "Layout";
|
||||
|
||||
/**
|
||||
* 非Layout菜单组件标识
|
||||
*/
|
||||
public final static String UN_LAYOUT = "un-layout/index.vue";
|
||||
|
||||
/**
|
||||
* 校验返回结果码
|
||||
*/
|
||||
public final static String UNIQUE = "0";
|
||||
public final static String NOT_UNIQUE = "1";
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.hcframe.base.module.auth.controller;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.module.auth.entity.OsSysMenu;
|
||||
import com.hcframe.base.module.auth.service.AuthFunctionService;
|
||||
import com.hcframe.base.module.auth.service.MenuService;
|
||||
import io.swagger.annotations.Api;
|
||||
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.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-09
|
||||
* @decription 权限接口
|
||||
*/
|
||||
@RestController
|
||||
@Api(tags = "权限管理")
|
||||
@RequestMapping("auth/function")
|
||||
public class AuthFunctionController {
|
||||
|
||||
@Autowired
|
||||
AuthFunctionService authService;
|
||||
|
||||
@Autowired
|
||||
MenuService menuService;
|
||||
|
||||
|
||||
@GetMapping("menu")
|
||||
public ResultVO getMenuResult() {
|
||||
List<OsSysMenu> menus = menuService.getMenuResult();
|
||||
return ResultVO.getSuccess(menuService.formatMenu(menus));
|
||||
}
|
||||
|
||||
@PostMapping("menu")
|
||||
public ResultVO addAuthResult(OsSysMenu osSysMenu) {
|
||||
return ResultVO.getSuccess(menuService.add(osSysMenu));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.hcframe.base.module.auth.controller;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.module.auth.service.FtUserService;
|
||||
import com.hcframe.base.module.log.annotation.LogAnno;
|
||||
import com.hcframe.base.module.shiro.service.ShiroService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* (FtUser)表控制层
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-02-11 19:29:10
|
||||
*/
|
||||
@RestController
|
||||
@Api(tags = "用户相关接口")
|
||||
@RequestMapping("ftUser")
|
||||
public class FtUserController {
|
||||
/**
|
||||
* 服务对象
|
||||
*/
|
||||
@Autowired
|
||||
private FtUserService ftUserService;
|
||||
|
||||
@Autowired
|
||||
ShiroService shiroService;
|
||||
|
||||
@ApiOperation(value = "用户登陆")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "username", value = "用户名", required = true),
|
||||
@ApiImplicitParam(name = "password", value = "密码", required = true),
|
||||
})
|
||||
//@LogAnno(operateType = "用户登录")
|
||||
@PostMapping("login")
|
||||
public ResultVO login(HttpServletRequest request, String username, String password) {
|
||||
return ftUserService.login(request, username, password);
|
||||
}
|
||||
|
||||
@LogAnno(operateType = "用户登出", isBefore = true)
|
||||
@ApiOperation(value = "用户登出")
|
||||
@PostMapping("/logout")
|
||||
public ResultVO logOut(HttpServletRequest request) {
|
||||
String token = request.getHeader("X-Access-Token");
|
||||
shiroService.logout(token);
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.hcframe.base.module.auth.dao;
|
||||
|
||||
import com.hcframe.base.common.Mapper;
|
||||
import com.hcframe.base.module.auth.entity.FtUser;
|
||||
|
||||
/**
|
||||
* (FtUser)表数据库访问层
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-02-11 19:29:10
|
||||
*/
|
||||
public interface FtUserDao extends Mapper<FtUser> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.hcframe.base.module.auth.dao;
|
||||
|
||||
import com.hcframe.base.common.Mapper;
|
||||
import com.hcframe.base.module.auth.entity.OsSysMenu;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单权限表(OsSysMenu)表数据库访问层
|
||||
*
|
||||
* @author makejava
|
||||
* @since 2020-12-09 09:57:20
|
||||
*/
|
||||
public interface OsSysMenuDao extends Mapper<OsSysMenu> {
|
||||
|
||||
List<OsSysMenu> selectMenu();
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.hcframe.base.module.auth.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* (FtUser)实体类
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-09-23 13:49:30
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
@Table(name = "FT_USER")
|
||||
public class FtUser implements Serializable {
|
||||
private static final long serialVersionUID = -44415286580890701L;
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(generator="JDBC")
|
||||
private Integer userId;
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
private String username;
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 手机号
|
||||
*/
|
||||
private String phone;
|
||||
/**
|
||||
* 用户类型,0未验证用户,1外部,2内部,3企业
|
||||
*/
|
||||
private Integer userType;
|
||||
/**
|
||||
* 启用/禁用
|
||||
*/
|
||||
private Integer enabled;
|
||||
/**
|
||||
* 用户信息主键
|
||||
*/
|
||||
private Integer userInfoId;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date createTime;
|
||||
/**
|
||||
* 修改时间
|
||||
*/
|
||||
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date updateTime;
|
||||
|
||||
private Integer orgId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.hcframe.base.module.auth.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Table;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 菜单权限表(OsSysMenu)实体类
|
||||
*
|
||||
* @author makejava
|
||||
* @since 2020-12-09 09:57:20
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
@Table(name = "OS_SYS_MENU")
|
||||
public class OsSysMenu implements Serializable {
|
||||
private static final long serialVersionUID = -36592644935215591L;
|
||||
|
||||
public static final String M = "M";
|
||||
public static final String C = "C";
|
||||
public static final String F = "F";
|
||||
public static final String I = "I";
|
||||
|
||||
|
||||
/**
|
||||
* 菜单ID
|
||||
*/
|
||||
private Long menuId;
|
||||
/**
|
||||
* 菜单名称
|
||||
*/
|
||||
private String menuName;
|
||||
/**
|
||||
* 父菜单ID
|
||||
*/
|
||||
private Long parentId;
|
||||
/**
|
||||
* 显示顺序
|
||||
*/
|
||||
private Integer orderNum;
|
||||
/**
|
||||
* 路由地址
|
||||
*/
|
||||
private String path;
|
||||
/**
|
||||
* 组件路径
|
||||
*/
|
||||
private String component;
|
||||
/**
|
||||
* 是否为外链(0是 1否)
|
||||
*/
|
||||
private String isFrame;
|
||||
/**
|
||||
* 是否缓存(0缓存 1不缓存)
|
||||
*/
|
||||
private String isCache;
|
||||
/**
|
||||
* 菜单类型(M目录 C菜单 F按钮)
|
||||
*/
|
||||
private String menuType;
|
||||
/**
|
||||
* 菜单状态(0显示 1隐藏)
|
||||
*/
|
||||
private String visible;
|
||||
/**
|
||||
* 菜单状态(0正常 1停用)
|
||||
*/
|
||||
private String status;
|
||||
/**
|
||||
* 权限标识
|
||||
*/
|
||||
private String perms;
|
||||
/**
|
||||
* 菜单图标
|
||||
*/
|
||||
private String icon;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createTime;
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private Date updateTime;
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
private String remark;
|
||||
/**
|
||||
* if true, will always show the root menu (default is false)
|
||||
* if false, hide the root menu when has less or equal than one children route
|
||||
*/
|
||||
private String alwaysShow;
|
||||
|
||||
/**
|
||||
* if false, the item will be hidden in breadcrumb (default is true)
|
||||
*/
|
||||
private String breadcrumb;
|
||||
/**
|
||||
* if true, the tag will affix in the tags-view
|
||||
*/
|
||||
private String affix;
|
||||
|
||||
private List<OsSysMenu> children;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.hcframe.base.module.auth.service;
|
||||
|
||||
public interface AuthFunctionService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hcframe.base.module.auth.service;
|
||||
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* (FtUser)表服务接口
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-02-11 19:29:10
|
||||
*/
|
||||
public interface FtUserService {
|
||||
|
||||
ResultVO login(HttpServletRequest request, String username, String password);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.hcframe.base.module.auth.service;
|
||||
|
||||
|
||||
import com.hcframe.base.module.auth.entity.OsSysMenu;
|
||||
import com.hcframe.base.module.auth.vo.RouterVo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface MenuService {
|
||||
|
||||
List<OsSysMenu> getMenuResult();
|
||||
|
||||
List<RouterVo> formatMenu(List<OsSysMenu> menus);
|
||||
|
||||
Object add(OsSysMenu osSysMenu);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.hcframe.base.module.auth.service.impl;
|
||||
|
||||
import com.hcframe.base.module.auth.service.AuthFunctionService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
|
||||
@Service
|
||||
public class AuthFunctionServiceImpl implements AuthFunctionService {
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.hcframe.base.module.auth.service.impl;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.config.FrameConfig;
|
||||
import com.hcframe.base.common.utils.MD5Util;
|
||||
import com.hcframe.base.common.utils.TokenProccessor;
|
||||
import com.hcframe.base.module.auth.dao.FtUserDao;
|
||||
import com.hcframe.base.module.auth.entity.FtUser;
|
||||
import com.hcframe.base.module.auth.service.FtUserService;
|
||||
import com.hcframe.base.module.shiro.dao.FtTokenDao;
|
||||
import com.hcframe.base.module.shiro.service.ShiroService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* (FtUser)表服务实现类
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-02-11 19:29:10
|
||||
*/
|
||||
@Service("ftUserService")
|
||||
public class FtUserServiceImpl implements FtUserService {
|
||||
|
||||
|
||||
/**
|
||||
* 用户失效时间
|
||||
*/
|
||||
private static int EXPIRE;
|
||||
|
||||
private final FtTokenDao ftTokenDao;
|
||||
private final FtUserDao ftUserDao;
|
||||
|
||||
|
||||
final
|
||||
ShiroService shiroService;
|
||||
|
||||
|
||||
|
||||
public FtUserServiceImpl(FtUserDao ftUserDao, ShiroService shiroService, FtTokenDao ftTokenDao) {
|
||||
this.ftUserDao = ftUserDao;
|
||||
this.shiroService = shiroService;
|
||||
this.ftTokenDao = ftTokenDao;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public void setHost(FrameConfig config) {
|
||||
FtUserServiceImpl.EXPIRE = config.getLoginTimeout() * 3600 * 1000;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ResultVO login(HttpServletRequest request, String username, String password) {
|
||||
FtUser ftUser = FtUser.builder().username(username).build();
|
||||
ftUser = ftUserDao.selectOne(ftUser);
|
||||
if (ftUser == null) {
|
||||
throw new ServiceException("用户名不存在");
|
||||
}
|
||||
if (ftUser.getEnabled() != 2) {
|
||||
if (MD5Util.isEqual(password, ftUser.getPassword())) {
|
||||
TokenProccessor tokenProccessor = TokenProccessor.getInstance();
|
||||
//生成一个token
|
||||
String token = tokenProccessor.makeToken();
|
||||
//过期时间
|
||||
Date now = new Date();
|
||||
Date expireTime = new Date(now.getTime() + EXPIRE);
|
||||
ResultVO resultVO = shiroService.createToken(String.valueOf(ftUser.getUserId()),token,expireTime);
|
||||
Map<String, Object> map = (Map<String, Object>) resultVO.getData();
|
||||
return ResultVO.getSuccess(map);
|
||||
} else {
|
||||
throw new ServiceException("用户名或密码错误!");
|
||||
}
|
||||
} else {
|
||||
throw new ServiceException("用户已被禁用,请联系管理员");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package com.hcframe.base.module.auth.service.impl;
|
||||
|
||||
import com.hcframe.base.common.utils.StringUtils;
|
||||
import com.hcframe.base.module.auth.constants.AuthConstants;
|
||||
import com.hcframe.base.module.auth.dao.OsSysMenuDao;
|
||||
import com.hcframe.base.module.auth.entity.OsSysMenu;
|
||||
import com.hcframe.base.module.auth.service.MenuService;
|
||||
import com.hcframe.base.module.auth.vo.MetaVo;
|
||||
import com.hcframe.base.module.auth.vo.RouterVo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class MenuServiceImpl implements MenuService {
|
||||
|
||||
@Autowired
|
||||
OsSysMenuDao osSysMenuDao;
|
||||
|
||||
@Override
|
||||
public List<OsSysMenu> getMenuResult() {
|
||||
List<OsSysMenu> osSysMenus = osSysMenuDao.selectMenu();
|
||||
return getChildPerms(osSysMenus, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据父节点的ID获取所有子节点
|
||||
*
|
||||
* @param list 分类表
|
||||
* @param parentId 传入的父节点ID
|
||||
* @return String
|
||||
*/
|
||||
public List<OsSysMenu> getChildPerms(List<OsSysMenu> list, int parentId) {
|
||||
List<OsSysMenu> returnList = new ArrayList<OsSysMenu>();
|
||||
for (Iterator<OsSysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
|
||||
OsSysMenu t = iterator.next();
|
||||
// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
|
||||
if (t.getParentId() == parentId) {
|
||||
recursionFn(list, t);
|
||||
returnList.add(t);
|
||||
}
|
||||
}
|
||||
return returnList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归列表
|
||||
*
|
||||
* @param list
|
||||
* @param t
|
||||
*/
|
||||
private void recursionFn(List<OsSysMenu> list, OsSysMenu t) {
|
||||
// 得到子节点列表
|
||||
List<OsSysMenu> childList = getChildList(list, t);
|
||||
t.setChildren(childList);
|
||||
for (OsSysMenu tChild : childList) {
|
||||
if (hasChild(list, tChild)) {
|
||||
recursionFn(list, tChild);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到子节点列表
|
||||
*/
|
||||
private List<OsSysMenu> getChildList(List<OsSysMenu> list, OsSysMenu t) {
|
||||
List<OsSysMenu> tlist = new ArrayList<OsSysMenu>();
|
||||
Iterator<OsSysMenu> it = list.iterator();
|
||||
while (it.hasNext()) {
|
||||
OsSysMenu n = it.next();
|
||||
if (n.getParentId().longValue() == t.getMenuId().longValue()) {
|
||||
tlist.add(n);
|
||||
}
|
||||
}
|
||||
return tlist;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否有子节点
|
||||
*/
|
||||
private boolean hasChild(List<OsSysMenu> list, OsSysMenu t) {
|
||||
return getChildList(list, t).size() > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<RouterVo> formatMenu(List<OsSysMenu> menus) {
|
||||
List<RouterVo> routers = new LinkedList<RouterVo>();
|
||||
for (OsSysMenu menu : menus) {
|
||||
RouterVo router = new RouterVo();
|
||||
router.setName(getRouteName(menu));
|
||||
router.setPath(getRouterPath(menu));
|
||||
router.setComponent(getComponent(menu));
|
||||
MetaVo metaVo = MetaVo
|
||||
.builder()
|
||||
.title(menu.getMenuName())
|
||||
.icon(menu.getIcon())
|
||||
.noCache(StringUtils.equals("0", menu.getIsCache()))
|
||||
.hidden("0".equals(menu.getVisible()))
|
||||
.breadcrumb("1".equals(menu.getBreadcrumb()))
|
||||
.affix("1".equals(menu.getAffix()))
|
||||
.alwaysShow("1".equals(menu.getAlwaysShow()))
|
||||
.build();
|
||||
List<OsSysMenu> cMenus = menu.getChildren();
|
||||
if (cMenus != null && !cMenus.isEmpty() && AuthConstants.TYPE_DIR.equals(menu.getMenuType())) {
|
||||
router.setRedirect("noredirect");
|
||||
router.setChildren(formatMenu(cMenus));
|
||||
} else if (isMeunFrame(menu)) {
|
||||
List<RouterVo> childrenList = new ArrayList<RouterVo>();
|
||||
RouterVo children = new RouterVo();
|
||||
children.setPath(menu.getPath());
|
||||
children.setComponent(menu.getComponent());
|
||||
children.setName(StringUtils.capitalize(menu.getPath()));
|
||||
metaVo = metaVo.toBuilder()
|
||||
.title(menu.getMenuName())
|
||||
.icon(menu.getIcon())
|
||||
.noCache(StringUtils.equals("0", menu.getIsCache()))
|
||||
.alwaysShow("1".equals(menu.getAlwaysShow()))
|
||||
.build();
|
||||
childrenList.add(children);
|
||||
router.setChildren(childrenList);
|
||||
} else if (cMenus == null || cMenus.isEmpty()) {
|
||||
metaVo.setAlwaysShow(false);
|
||||
}
|
||||
router.setMeta(metaVo);
|
||||
routers.add(router);
|
||||
}
|
||||
return routers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object add(OsSysMenu osSysMenu) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取路由名称
|
||||
*
|
||||
* @param menu 菜单信息
|
||||
* @return 路由名称
|
||||
*/
|
||||
public String getRouteName(OsSysMenu menu) {
|
||||
String routerName = StringUtils.capitalize(menu.getPath());
|
||||
// 非外链并且是一级目录(类型为目录)
|
||||
if (isMeunFrame(menu)) {
|
||||
routerName = StringUtils.EMPTY;
|
||||
}
|
||||
return routerName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取路由地址
|
||||
*
|
||||
* @param menu 菜单信息
|
||||
* @return 路由地址
|
||||
*/
|
||||
public String getRouterPath(OsSysMenu menu) {
|
||||
String routerPath = menu.getPath();
|
||||
// 非外链并且是一级目录(类型为目录)
|
||||
if (0 == menu.getParentId().intValue() && AuthConstants.TYPE_DIR.equals(menu.getMenuType())
|
||||
&& AuthConstants.NO_FRAME.equals(menu.getIsFrame())) {
|
||||
routerPath = "/" + menu.getPath();
|
||||
}
|
||||
// 非外链并且是一级目录(类型为菜单)
|
||||
else if (isMeunFrame(menu)) {
|
||||
routerPath = "/";
|
||||
}
|
||||
return routerPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取组件信息
|
||||
*
|
||||
* @param menu 菜单信息
|
||||
* @return 组件信息
|
||||
*/
|
||||
public String getComponent(OsSysMenu menu) {
|
||||
String component = AuthConstants.LAYOUT;
|
||||
if (StringUtils.isNotEmpty(menu.getComponent()) && !isMeunFrame(menu)) {
|
||||
component = menu.getComponent();
|
||||
}
|
||||
if (StringUtils.isEmpty(menu.getComponent())&&isNotParentMenuFrame(menu)) {
|
||||
component = AuthConstants.UN_LAYOUT;
|
||||
}
|
||||
return component;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为菜单内部跳转
|
||||
*
|
||||
* @param menu 菜单信息
|
||||
* @return 结果
|
||||
*/
|
||||
public boolean isMeunFrame(OsSysMenu menu) {
|
||||
return menu.getParentId().intValue() == 0 && AuthConstants.TYPE_MENU.equals(menu.getMenuType())
|
||||
&& menu.getIsFrame().equals(AuthConstants.NO_FRAME);
|
||||
}
|
||||
|
||||
public boolean isNotParentMenuFrame(OsSysMenu menu) {
|
||||
return menu.getParentId().intValue() != 0 && AuthConstants.TYPE_DIR.equals(menu.getMenuType())
|
||||
&& menu.getIsFrame().equals(AuthConstants.NO_FRAME);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**/
|
||||
package com.hcframe.base.module.auth.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 路由显示信息
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
public class MetaVo implements Serializable {
|
||||
private static final long serialVersionUID = -4261993881269135509L;
|
||||
/**
|
||||
* 设置该路由在侧边栏和面包屑中展示的名字
|
||||
*/
|
||||
private String title;
|
||||
|
||||
/**
|
||||
* 设置该路由的图标,对应路径src/assets/icons/svg
|
||||
*/
|
||||
private String icon;
|
||||
|
||||
/**
|
||||
* 设置为true,则不会被 <keep-alive>缓存
|
||||
*/
|
||||
private boolean noCache;
|
||||
|
||||
/**
|
||||
* 设置为是否隐藏,true为隐藏
|
||||
*/
|
||||
private boolean hidden;
|
||||
|
||||
/**
|
||||
* if true, will always show the root menu (default is false)
|
||||
* if false, hide the root menu when has less or equal than one children route
|
||||
*/
|
||||
private boolean alwaysShow;
|
||||
|
||||
/**
|
||||
* if false, the item will be hidden in breadcrumb (default is true)
|
||||
*/
|
||||
private boolean breadcrumb;
|
||||
/**
|
||||
* if true, the tag will affix in the tags-view
|
||||
*/
|
||||
private boolean affix;
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.hcframe.base.module.auth.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 路由配置信息
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
public class RouterVo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 8361861823516461515L;
|
||||
/**
|
||||
* 路由名字
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
* 路由地址
|
||||
*/
|
||||
private String path;
|
||||
|
||||
/**
|
||||
* 重定向地址,当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
|
||||
*/
|
||||
private String redirect;
|
||||
|
||||
/**
|
||||
* 组件地址
|
||||
*/
|
||||
private String component;
|
||||
|
||||
/**
|
||||
* 其他元素
|
||||
*/
|
||||
private MetaVo meta;
|
||||
|
||||
/**
|
||||
* 子路由
|
||||
*/
|
||||
private List<RouterVo> children;
|
||||
|
||||
}
|
||||
22
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/CacheService.java
vendored
Normal file
22
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/CacheService.java
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
package com.hcframe.base.module.cache;
|
||||
|
||||
import com.hcframe.base.module.cache.emum.CacheType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface CacheService {
|
||||
|
||||
void initTableCache();
|
||||
|
||||
<T> T getCacheValue(CacheType name, Object key, Class<T> tClass);
|
||||
|
||||
boolean save(CacheType name,Object key,Object data,Class<?> tClass) ;
|
||||
|
||||
boolean save(String key, Object data, Class<?> tClass);
|
||||
|
||||
boolean delete(String typeName);
|
||||
|
||||
boolean saveBatich(List<Object> key);
|
||||
|
||||
boolean deleteBatch(String ids);
|
||||
}
|
||||
21
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/base/BaseCache.java
vendored
Normal file
21
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/base/BaseCache.java
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.hcframe.base.module.cache.base;
|
||||
|
||||
import org.springframework.cache.Cache;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @description 缓存操作基础方法
|
||||
* @date 2020-12-31
|
||||
*/
|
||||
public interface BaseCache {
|
||||
|
||||
<T> T get(String name, Object key, Class<T> tClass);
|
||||
|
||||
void add(String name, Object key, Object data,Class<?> tClass);
|
||||
|
||||
void update(String name, Object key, Object data,Class<?> tClass);
|
||||
|
||||
boolean delete(String name, Object key);
|
||||
|
||||
Cache getCache(String name);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.hcframe.base.module.cache.base.impl;
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.module.cache.base.BaseCache;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @description 缓存操作基础方法实现类
|
||||
* @date 2020-12-31
|
||||
*/
|
||||
@Component
|
||||
public class BaseCacheImpl implements BaseCache {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(BaseCacheImpl.class);
|
||||
|
||||
@Autowired
|
||||
private CacheManager cacheManager;
|
||||
|
||||
@Override
|
||||
public <T> T get(String name, Object key, Class<T> tClass) {
|
||||
Cache cache = getCache(name);
|
||||
return cache.get(key, tClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(String name, Object key, Object data,Class<?> tClass) {
|
||||
Cache cache = getCache(name);
|
||||
if (tClass.isInstance(data)) {
|
||||
cache.put(key, tClass.cast(data));
|
||||
} else {
|
||||
throw new ServiceException("data 类型不匹配!");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(String name, Object key, Object data,Class<?> tClass) {
|
||||
Cache cache = getCache(name);
|
||||
if (tClass.isInstance(data)) {
|
||||
cache.put(key, tClass.cast(data));
|
||||
} else {
|
||||
throw new ServiceException("data 类型不匹配!");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(String name, Object key) {
|
||||
Cache cache = getCache(name);
|
||||
return cache.evictIfPresent(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cache getCache(String name) {
|
||||
return cacheManager.getCache(name);
|
||||
}
|
||||
}
|
||||
15
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/emum/CacheType.java
vendored
Normal file
15
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/emum/CacheType.java
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.hcframe.base.module.cache.emum;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @description 缓存类型枚举类
|
||||
* @date 2020-12-31
|
||||
*/
|
||||
public enum CacheType {
|
||||
// 表信息缓存
|
||||
tableCache,
|
||||
// 基表信息缓存
|
||||
baseCache,
|
||||
// 数据库连接缓存
|
||||
datasourceCache
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.hcframe.base.module.cache.impl;
|
||||
|
||||
import com.hcframe.base.module.cache.CacheService;
|
||||
import com.hcframe.base.module.cache.emum.CacheType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class DatasourceCache implements CacheService {
|
||||
|
||||
@Autowired
|
||||
private CacheManager cacheManager;
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(DatasourceCache.class);
|
||||
|
||||
@Override
|
||||
public void initTableCache() {
|
||||
logger.info("加载DatasorceCache");
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T getCacheValue(CacheType name, Object key, Class<T> tClass) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean save(CacheType name, Object key, Object data, Class<?> tClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean save(String key, Object data, Class<?> tClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(String typeName) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveBatich(List<Object> key) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteBatch(String ids) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
129
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/impl/TableCache.java
vendored
Normal file
129
hcframe-parent/hcframe-base/src/main/java/com/hcframe/base/module/cache/impl/TableCache.java
vendored
Normal file
@@ -0,0 +1,129 @@
|
||||
package com.hcframe.base.module.cache.impl;
|
||||
|
||||
import com.hcframe.base.common.utils.JudgeException;
|
||||
import com.hcframe.base.module.cache.CacheService;
|
||||
import com.hcframe.base.module.cache.base.BaseCache;
|
||||
import com.hcframe.base.module.cache.emum.CacheType;
|
||||
import com.hcframe.base.module.data.controller.TableController;
|
||||
import com.hcframe.base.module.data.module.BaseMapper;
|
||||
import com.hcframe.base.module.data.module.BaseMapperImpl;
|
||||
import com.hcframe.base.module.tableconfig.dao.OsSysTableMapper;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-30
|
||||
* @description 初始化配置表缓存操作类
|
||||
*/
|
||||
@Component
|
||||
@Qualifier("table")
|
||||
public class TableCache implements CacheService {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(TableController.class);
|
||||
// 基表开头
|
||||
public static final String BASE = "BASE_";
|
||||
public static final String TABLE = "table";
|
||||
// 状态
|
||||
public static ConcurrentMap<String, Integer> status = new ConcurrentHashMap<String, Integer>();
|
||||
|
||||
@Autowired
|
||||
OsSysTableMapper osSysTableMapper;
|
||||
|
||||
@Qualifier(BaseMapperImpl.BASE)
|
||||
@Autowired
|
||||
BaseMapper baseMapper;
|
||||
|
||||
@Autowired
|
||||
BaseCache baseCache;
|
||||
|
||||
// 初始化缓存加载
|
||||
@Override
|
||||
public void initTableCache() {
|
||||
List<OsSysTable> list = osSysTableMapper.selectAll();
|
||||
// 将数据写入缓存
|
||||
for (OsSysTable osSysTable : list) {
|
||||
logger.info("loading tableInfo : " + osSysTable.getTableContent());
|
||||
// 写入缓存
|
||||
baseCache.add(
|
||||
CacheType.tableCache.toString(),
|
||||
osSysTable.getTableAlias(),
|
||||
osSysTableMapper.getTableAllInfo(osSysTable.getTableAlias()),
|
||||
OsSysTable.class
|
||||
);
|
||||
if (osSysTable.getTableName().startsWith(BASE)) {
|
||||
logger.info("loading baseTable : " + osSysTable.getTableName());
|
||||
List<Map<String, Object>> baseList = baseMapper.selectAll(osSysTable.getTableName());
|
||||
// 写入缓存
|
||||
baseCache.add(
|
||||
CacheType.baseCache.toString(),
|
||||
osSysTable.getTableAlias(),
|
||||
baseList,
|
||||
List.class
|
||||
);
|
||||
}
|
||||
}
|
||||
logger.info("data init finished");
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T getCacheValue(CacheType name, Object key, Class<T> tClass) {
|
||||
T t = baseCache.get(name.toString(), key, tClass);
|
||||
// 若缓存过期,重新加载
|
||||
if (t == null) {
|
||||
switch (name) {
|
||||
case tableCache:
|
||||
OsSysTable osSysTable = osSysTableMapper.getTableAllInfo((String) key);
|
||||
JudgeException.isNull(osSysTable, "can not find key " + key + " in cache which cache name is " + name);
|
||||
baseCache.add(name.toString(), key, osSysTableMapper.getTableAllInfo((String)key), OsSysTable.class);
|
||||
break;
|
||||
case baseCache:
|
||||
OsSysTable osSysTable1 = getCacheValue(CacheType.tableCache, key, OsSysTable.class);
|
||||
List<Map<String, Object>> baseList = baseMapper.selectAll(osSysTable1.getTableName());
|
||||
JudgeException.isNull(baseList, "can not find key " + key + " in cache which cache name is " + name);
|
||||
baseCache.add(name.toString(), key, baseList, List.class);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return baseCache.get(name.toString(), key, tClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean save(CacheType name, Object key, Object data, Class<?> tClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean save(String key, Object data, Class<?> tClass) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(String typeName) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveBatich(List<Object> key) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean deleteBatch(String ids) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isRuning() {
|
||||
return !status.isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hcframe.base.module.data.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 忽略字段
|
||||
*
|
||||
* @author lhc
|
||||
*/
|
||||
// 方法注解
|
||||
@Target(ElementType.FIELD)
|
||||
// 运行时可见
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface DataIgnore {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.hcframe.base.module.data.constants;
|
||||
|
||||
public enum FieldConstants {
|
||||
DELETED,VERSION,UPDATE_TIME,CREATE_TIME
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.hcframe.base.module.data.constants;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-10
|
||||
* @decription 权限常亮信息
|
||||
*/
|
||||
public class QueryConstants {
|
||||
public static final int L_CURVES = 1;
|
||||
public static final int R_CURVES = 2;
|
||||
|
||||
public static final int AND = 1;
|
||||
public static final int OR = 2;
|
||||
|
||||
public static final int EQUAL = 1;
|
||||
public static final int LIKE = 2;
|
||||
public static final int IN = 3;
|
||||
public static final int BETWEEN = 4;
|
||||
public static final int LT = 5;
|
||||
public static final int GT = 6;
|
||||
public static final int LTE = 7;
|
||||
public static final int GTE = 8;
|
||||
|
||||
public static final String QUERY = "query";
|
||||
public static final String JOIN = "join";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.hcframe.base.module.data.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class IndexController {
|
||||
|
||||
@GetMapping("/")
|
||||
public String getIndex(){
|
||||
return "index";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.hcframe.base.module.data.controller;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.common.utils.TableNameUtil;
|
||||
import com.hcframe.base.module.data.service.TableService;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiImplicitParams;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/***
|
||||
* @description 控制器提供接口
|
||||
*/
|
||||
@Api(tags = "通用增删改查接口")
|
||||
@RequestMapping("common")
|
||||
@RestController// 控制器注解,告诉Spring框架进行管理,并返回Json格式字符串,将@ResponeseBody 和 @Controller注解功能合并的注解
|
||||
public class TableController {
|
||||
|
||||
final
|
||||
TableService tableService;
|
||||
|
||||
final
|
||||
TableNameUtil tableNameUtil;
|
||||
|
||||
public TableController(TableService tableService, TableNameUtil tableNameUtil) {
|
||||
this.tableService = tableService;
|
||||
this.tableNameUtil = tableNameUtil;
|
||||
}
|
||||
|
||||
@ApiOperation(value = "保存接口(不带保存日期)")
|
||||
@PostMapping("/{typeName}")
|
||||
public ResultVO<Integer> save(@PathVariable String typeName, @RequestParam Map<String, Object> map) {
|
||||
return ResultVO.getSuccess(tableService.save(tableNameUtil.getTableName(typeName), map));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "保存接口(带保存日期)")
|
||||
@PostMapping("/{typeName}/date")
|
||||
public ResultVO<Map<String,Object>> saveWithDate(@PathVariable String typeName, @RequestParam Map<String, Object> map) {
|
||||
return tableService.saveWithDate(tableNameUtil.getTableName(typeName), map);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "更新接口")
|
||||
@PutMapping({"/{typeName}/{version}","/{typeName}"})
|
||||
public ResultVO<Integer> update(@PathVariable String typeName, @RequestParam Map<String, Object> map,@PathVariable(required = false) Integer version) {
|
||||
return tableService.update(tableNameUtil.getTableName(typeName), map,version);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "更新接口(带更改日期)")
|
||||
@PutMapping({"/{typeName}/{version}/date","/{typeName}/date"})
|
||||
public ResultVO<Integer> updateWithDate(@PathVariable String typeName, @RequestParam Map<String, Object> map,@PathVariable(required = false) Integer version) {
|
||||
return tableService.updateWithDate(tableNameUtil.getTableName(typeName), map,version);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "删除接口(可批量)")
|
||||
@DeleteMapping("/{typeName}")
|
||||
@ApiImplicitParam(name = "ids", value = "id主键的数组的toString", required = true)
|
||||
public ResultVO<Integer> delete(@PathVariable String typeName, String ids) {
|
||||
return tableService.delete(tableNameUtil.getTableName(typeName), ids);
|
||||
}
|
||||
|
||||
|
||||
@ApiOperation(value = "逻辑删除(可批量)")
|
||||
@DeleteMapping("/{typeName}/logic")
|
||||
@ApiImplicitParam(name = "ids", value = "id主键的数组的toString", required = true)
|
||||
public ResultVO<Integer> logicDelete(@PathVariable String typeName,String ids) {
|
||||
return tableService.logicDelete(tableNameUtil.getTableName(typeName), ids);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取单表数据接口(带分页)")
|
||||
@GetMapping("/{typeName}")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "typeName", value = " 类型", type = "path", required = true),
|
||||
@ApiImplicitParam(name = "data", value = " JSON.stringify()后的数据,主要为查询条件"),
|
||||
})
|
||||
public ResultVO<PageInfo<Map<String,Object>>> searchTables(@PathVariable String typeName, String data, WebPageInfo webPageInfo) {
|
||||
return ResultVO.getSuccess(tableService.searchSingleTables(data, tableNameUtil.getTableName(typeName), webPageInfo));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取连表数据接口(带分页)")
|
||||
@GetMapping("/{typeName}/join")
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "typeName", value = " 类型", type = "path", required = true),
|
||||
@ApiImplicitParam(name = "data", value = " JSON.stringify()后的数据,主要为查询条件"),
|
||||
})
|
||||
public ResultVO<PageInfo<Map<String,Object>>> searchJoinTables(@PathVariable String typeName, String data, WebPageInfo webPageInfo) {
|
||||
return ResultVO.getSuccess(tableService.searchJoinTables(data, webPageInfo,tableNameUtil.getTableName(typeName)));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取单表接口(不带分页)")
|
||||
@GetMapping("/getListNoPage/{typeName}")
|
||||
public ResultVO<List<Map<String,Object>>> getListNoPage(@PathVariable String typeName, @RequestParam Map<String, Object> map) {
|
||||
return tableService.getListNoPage(tableNameUtil.getTableName(typeName), map);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取表格全部信息")
|
||||
@GetMapping("/{typeName}/getTableInfo/")
|
||||
public ResultVO<OsSysTable> getTableInfo(@PathVariable String typeName) {
|
||||
return ResultVO.getSuccess(tableNameUtil.getTableAllInfo(typeName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "批量更新")
|
||||
@PutMapping("/{typeName}/batch")
|
||||
public ResultVO<Integer> updateBatch(@PathVariable String typeName, @RequestParam Map<String, Object> map) {
|
||||
return tableService.updateBatch(tableNameUtil.getTableName(typeName), map);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "批量更新(带日期)")
|
||||
@PutMapping("/{typeName}/batchWithDate")
|
||||
public ResultVO<Integer> updateBatchWithDate(@PathVariable String typeName, @RequestParam Map<String, Object> map) {
|
||||
return tableService.updateBatchWithDate(tableNameUtil.getTableName(typeName), map);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "批量新增")
|
||||
@PostMapping("/{typeName}/batch")
|
||||
public ResultVO<Integer> saveBatch(@PathVariable String typeName, @RequestParam String data) {
|
||||
return tableService.saveBatch(tableNameUtil.getTableName(typeName), data);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "批量新增(带日期)")
|
||||
@PostMapping("/{typeName}/batchWithDate")
|
||||
public ResultVO<Integer> saveBatchWithDate(@PathVariable String typeName, @RequestParam String data) {
|
||||
return tableService.saveBatchWithDate(tableNameUtil.getTableName(typeName), data);
|
||||
}
|
||||
|
||||
@ApiOperation(value = "获取基表信息")
|
||||
@GetMapping("/getBaseTableInfo")
|
||||
public ResultVO<Map<String,Object>> getBaseTableInfo(String tableNames) {
|
||||
return tableService.getBaseTableInfo(tableNames);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.hcframe.base.module.data.dao;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface TableMapper {
|
||||
|
||||
List<Map<String ,Object>> findAllTables(@Param("tableName") String tableName);
|
||||
|
||||
List<Map<String, Object>> findAllTablesWithField(@Param("fields") String fields, @Param("tableName") String tableName);
|
||||
|
||||
List<Map<String ,Object>> findByEqual(@Param("tableName") String tableName, @Param("info") Map<String, Object> map);
|
||||
|
||||
List<Map<String ,Object>> findByLike(@Param("tableName") String tableName, @Param("info") Map<String, Object> map);
|
||||
|
||||
int deleteByPrimary(@Param("ids") String[] id, @Param("tableName") String tableName, @Param("pkName") String pkName);
|
||||
|
||||
int saveInfo(@Param("info") Map<String, Object> map, @Param("tableName") String tableName);
|
||||
|
||||
int saveInfoWithNull(@Param("info") Map<String, Object> map, @Param("tableName") String tableName);
|
||||
|
||||
int saveInfoWithOracle(@Param("info") Map<String, Object> map, @Param("tableName") String tableName);
|
||||
|
||||
int updateInfo(@Param("info") Map<String, Object> map, @Param("tableName") String tableName);
|
||||
|
||||
int updateInfoWithNull(@Param("info") Map<String, Object> map, @Param("tableName") String tableName);
|
||||
|
||||
int updateByWhere(@Param("info") Map<String, Object> map, @Param("tableName") String tableName, @Param("sql") String sql);
|
||||
|
||||
int updateByWhereWithNull(@Param("info") Map<String, Object> map, @Param("tableName") String tableName, @Param("sql") String sql);
|
||||
|
||||
int deleteByWhere(@Param("tableName") String tableName, @Param("sql") String sql);
|
||||
|
||||
List<Map<String, Object>> useSql(@Param("sql") String sql);
|
||||
|
||||
Map<String, Object> userSqlByOne(@Param("sql") String sql);
|
||||
|
||||
Object useSqlByTest(@Param("sql") String sql);
|
||||
|
||||
List<Map<String, Object>> getListNoPage(@Param("typeName") String tableName, @Param("info") Map<String, Object> map);
|
||||
|
||||
Object getSequence(@Param("tableName") String tableName);
|
||||
|
||||
int createSequence(@Param("tableName") String tableName, @Param("lastId")Object lastId);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.hcframe.base.module.data.exception;
|
||||
|
||||
public class BaseMapperException extends RuntimeException{
|
||||
private static final long serialVersionUID = -3691286451456700443L;
|
||||
public BaseMapperException() {
|
||||
}
|
||||
|
||||
public BaseMapperException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public BaseMapperException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public BaseMapperException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public BaseMapperException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.hcframe.base.module.data.exception;
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.utils.StringUtils;
|
||||
|
||||
public class SqlException {
|
||||
|
||||
public static void operation(int i, String str) {
|
||||
if (StringUtils.isEmpty(str)) {
|
||||
str = "操作失败";
|
||||
}
|
||||
if (i < 1) {
|
||||
throw new ServiceException(str);
|
||||
}
|
||||
}
|
||||
|
||||
public static void base(int i, String str) {
|
||||
if (StringUtils.isEmpty(str)) {
|
||||
str = "操作失败";
|
||||
}
|
||||
if (i < 1) {
|
||||
throw new BaseMapperException(str);
|
||||
}
|
||||
}
|
||||
|
||||
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
|
||||
int m = nums1.length, n = nums2.length;
|
||||
if (m == 0) {
|
||||
return getAvg(n, nums2);
|
||||
}
|
||||
if (n == 0) {
|
||||
return getAvg(m, nums1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static double getAvg(int n, int[] nums) {
|
||||
if (n % 2 == 0) {
|
||||
return (nums[n / 2] + nums[n / 2 - 1]) / 2.0;
|
||||
} else {
|
||||
return (nums[n / 2]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
*/
|
||||
public interface BaseMapper {
|
||||
|
||||
<E> int save(DataMap<E> dataMap);
|
||||
|
||||
int save(String tableName, String pkName, Map<String, Object> data);
|
||||
|
||||
<E> int save(E e);
|
||||
|
||||
<E> int updateByPk(DataMap<E> dataMap);
|
||||
|
||||
int updateByPk(String tableName, String pkName, Map<String, Object> data);
|
||||
|
||||
int updateByPk(OsSysTable osSysTable, Map<String, Object> data);
|
||||
|
||||
<E> int updateByPk(E e);
|
||||
|
||||
<E> int updateInPk(DataMap<E> dataMap);
|
||||
|
||||
<E, A> int updateInPk(E e, List<A> ids);
|
||||
|
||||
<E> int updateInPk(String tableName, String pkName, List<E> ids, Map<String, Object> data);
|
||||
|
||||
<E> int updateInPk(OsSysTable osSysTable, List<E> ids, Map<String, Object> data);
|
||||
|
||||
<E> int updateByCondition(DataMap<E> dataMap, Condition condition);
|
||||
|
||||
int updateByCondition(String tableName, Map<String, Object> data, Condition condition);
|
||||
|
||||
<E> int deleteByPk(DataMap<E> dataMap);
|
||||
|
||||
int deleteByPk(String tableName, String pkName, Object pkValue);
|
||||
|
||||
int deleteByPk(OsSysTable osSysTable, Object pkValue);
|
||||
|
||||
<E> int deleteInPk(String tableName, String pkName, List<E> ids);
|
||||
|
||||
<E> int deleteInPk(DataMap<E> dataMap);
|
||||
|
||||
<E> int deleteInPk(OsSysTable osSysTable, List<E> ids);
|
||||
|
||||
<E> int deleteByCondition(DataMap<E> dataMap, Condition condition);
|
||||
|
||||
int deleteByCondition(String tableName, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectAll(String tableName);
|
||||
|
||||
<E> List<Map<String, Object>> selectByEqual(DataMap<E> dataMap, Map<String, Object> map);
|
||||
|
||||
List<Map<String, Object>> selectByEqual(String tableName, Map<String, Object> map);
|
||||
|
||||
<E> PageInfo<Map<String, Object>> selectByEqual(DataMap<E> dataMap, Map<String, Object> map, WebPageInfo webPageInfo);
|
||||
|
||||
PageInfo<Map<String, Object>> selectByEqual(String tableName, Map<String, Object> map, WebPageInfo webPageInfo);
|
||||
|
||||
<E> Map<String, Object> selectOneByEqual(DataMap<E> dataMap, Map<String, Object> map);
|
||||
|
||||
<E> Map<String, Object> selectByPk(DataMap<E> dataMap);
|
||||
|
||||
Map<String, Object> selectByPk(OsSysTable osSysTable, Object pkValue);
|
||||
|
||||
Map<String, Object> selectByPk(String tableName, String pkName, Object pkValue);
|
||||
|
||||
List<Map<String, Object>> selectByCondition(Condition condition);
|
||||
|
||||
<E> List<Map<String, Object>> selectByCondition(DataMap<E> dataMap, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectByCondition(String tableName, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectByCondition(String tableName, List<String> fieldList, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectByCondition(String tableName, String fieldList, Condition condition);
|
||||
|
||||
PageInfo<Map<String, Object>> selectByCondition(Condition condition, WebPageInfo webPageInfo);
|
||||
|
||||
<E> PageInfo<Map<String, Object>> selectByCondition(DataMap<E> dataMap, Condition condition, WebPageInfo webPageInfo);
|
||||
|
||||
PageInfo<Map<String, Object>> selectByCondition(String tableName, Condition condition, WebPageInfo webPageInfo);
|
||||
|
||||
PageInfo<Map<String, Object>> selectByCondition(String tableName, List<String> fieldList, Condition condition, WebPageInfo webPageInfo);
|
||||
|
||||
PageInfo<Map<String, Object>> selectByCondition(String tableName, String fieldList, Condition condition, WebPageInfo webPageInfo);
|
||||
|
||||
<E> Map<String, Object> selectOneByCondition(DataMap<E> dataMap, Condition condition);
|
||||
|
||||
Map<String, Object> selectOneByCondition(String tableName, Condition condition);
|
||||
|
||||
Map<String, Object> selectOneByCondition(String tableName, List<String> fieldList, Condition condition);
|
||||
|
||||
Map<String, Object> selectOneByCondition(String tableName, String fieldList, Condition condition);
|
||||
|
||||
Map<String, Object> selectOneByCondition(Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectJoinByCondition(String tableName, JoinCondition joinCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectJoinByCondition(String tableName, List<JoinCondition> joinCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectLeftJoinByCondition(String tableName, JoinCondition joinCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectLeftJoinByCondition(String tableName, List<JoinCondition> joinCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectRightJoinByCondition(String tableName, JoinCondition joinCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectRightJoinByCondition(String tableName, List<JoinCondition> joinCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectionByCondition(SelectCondition selectCondition, Condition condition);
|
||||
|
||||
List<Map<String, Object>> selectSql(String sql);
|
||||
|
||||
PageInfo<Map<String, Object>> selectSqlByPage(String sql, WebPageInfo webPageInfo);
|
||||
|
||||
Map<String, Object> selectOneSql(String sql);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,600 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.common.utils.MyPageHelper;
|
||||
import com.hcframe.base.common.utils.StringUtils;
|
||||
import com.hcframe.base.module.data.dao.TableMapper;
|
||||
import com.hcframe.base.module.data.exception.BaseMapperException;
|
||||
import com.hcframe.base.module.data.exception.SqlException;
|
||||
import com.hcframe.base.module.datasource.dynamic.DBContextHolder;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
import com.hcframe.base.module.datasource.utils.DataSourceUtil;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service("base")
|
||||
public class BaseMapperImpl implements BaseMapper {
|
||||
|
||||
public static final String BASE = "base";
|
||||
|
||||
final TableMapper tableMapper;
|
||||
|
||||
public BaseMapperImpl(TableMapper tableMapper) {
|
||||
this.tableMapper = tableMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public <E> int save(DataMap<E> dataMap) {
|
||||
String key;
|
||||
key = DBContextHolder.getDataSource();
|
||||
DatasourceConfig datasourceConfig = DataSourceUtil.get(key);
|
||||
JudgesNull(dataMap.getData(), "data can not be null!");
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
if (StringUtils.isEmpty(dataMap.getPkName())) {
|
||||
dataMap.setPkName("ID");
|
||||
}
|
||||
int i;
|
||||
if (datasourceConfig.getCommonType().equals(DataUnit.ORACLE)||datasourceConfig.getCommonType().equals(DataUnit.DAMENG)) {
|
||||
if (org.springframework.util.StringUtils.isEmpty(dataMap.get(dataMap.getPkName()))) {
|
||||
Object id = getSequence(dataMap.getTableName(), dataMap.getPkName());
|
||||
dataMap.toBuilder().add(dataMap.getPkName(), id);
|
||||
dataMap.setPkValue(id);
|
||||
}
|
||||
i = tableMapper.saveInfoWithOracle(dataMap.getData(), dataMap.getTableName());
|
||||
} else {
|
||||
i = tableMapper.saveInfoWithNull(dataMap.getData(), dataMap.getTableName());
|
||||
Object id = dataMap.getData().get("id");
|
||||
dataMap.toBuilder().add(dataMap.getPkName(), id).build();
|
||||
dataMap.setPkValue(id);
|
||||
}
|
||||
SqlException.base(i, "保存失败");
|
||||
dataMap.toBuilder().remove("id");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public int save(String tableName, String pkName, Map<String, Object> data) {
|
||||
JudgesNull(tableName, "data can not be null!");
|
||||
JudgesNull(data, "tableName can not be null!");
|
||||
String key = DBContextHolder.getDataSource();
|
||||
DatasourceConfig datasourceConfig = DataSourceUtil.get(key);
|
||||
if (StringUtils.isEmpty(pkName)) {
|
||||
pkName = "ID";
|
||||
}
|
||||
int i;
|
||||
if (datasourceConfig.getCommonType().equals(DataUnit.ORACLE)||datasourceConfig.getCommonType().equals(DataUnit.DAMENG)) {
|
||||
if (org.springframework.util.StringUtils.isEmpty(data.get(pkName))) {
|
||||
data.put(pkName, getSequence(tableName, pkName));
|
||||
}
|
||||
i = tableMapper.saveInfoWithOracle(data, tableName);
|
||||
} else {
|
||||
i = tableMapper.saveInfoWithNull(data, tableName);
|
||||
data.put(pkName, data.get("id"));
|
||||
}
|
||||
SqlException.base(i, "保存失败");
|
||||
data.remove("id");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int save(E e) {
|
||||
DataMap<E> dataMap = DataMap.<E>builder().obj(e).build();
|
||||
int i = save(dataMap);
|
||||
dataMap.set(StringUtils.toCamelCase(dataMap.getPkName()),dataMap.getPkValue());
|
||||
OsSysTable sysTable = (OsSysTable) dataMap.getObj();
|
||||
System.out.println(sysTable.getTableId()+"++++++++++++");
|
||||
return i;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public <E> int updateByPk(DataMap<E> dataMap) {
|
||||
JudgesNull(dataMap.getData(), "data can not be null!");
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(dataMap.getPkName(), "pkName can not be null!");
|
||||
JudgesNull(dataMap.getPkValue(), "pkValue can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andEqual(dataMap.getPkName(), dataMap.getPkValue())
|
||||
.build();
|
||||
int i = tableMapper.updateByWhere(dataMap.getData(), dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateByPk(String tableName, String pkName, Map<String, Object> data) {
|
||||
JudgesNull(data, "data can not be null!");
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
JudgesNull(pkName, "pkName can not be null!");
|
||||
JudgesNull(data.get(pkName), "pkValue can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andEqual(pkName, data.get(pkName))
|
||||
.build();
|
||||
data.remove(pkName);
|
||||
int i = tableMapper.updateByWhere(data, tableName, condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateByPk(OsSysTable osSysTable, Map<String, Object> data) {
|
||||
JudgesNull(data, "data can not be null!");
|
||||
JudgesNull(osSysTable.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(osSysTable.getTablePk(), "pkName can not be null!");
|
||||
JudgesNull(data.get(osSysTable.getTablePk()), "pkValue can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andEqual(osSysTable.getTablePk(), data.get(osSysTable.getTablePk()))
|
||||
.build();
|
||||
int i = tableMapper.updateByWhere(data, osSysTable.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int updateByPk(E e) {
|
||||
return updateByPk(DataMap.<E>builder().obj(e).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E, A> int updateInPk(E e, List<A> ids) {
|
||||
DataMap<E> dataMap = DataMap.<E>builder().obj(e).build();
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(dataMap.getPkName(), ids)
|
||||
.build();
|
||||
int i = tableMapper.updateByWhere(dataMap.getData(), dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public <E> int updateInPk(DataMap<E> dataMap) {
|
||||
JudgesNull(dataMap.getData(), "data can not be null!");
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(dataMap.getPkName(), "pkName can not be null!");
|
||||
JudgesNull(dataMap.getIds(), "ids can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(dataMap.getPkName(), dataMap.getIdList())
|
||||
.build();
|
||||
int i = tableMapper.updateByWhere(dataMap.getData(), dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int updateInPk(String tableName, String pkName, List<E> ids, Map<String, Object> data) {
|
||||
JudgesNull(data, "data can not be null!");
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
JudgesNull(pkName, "pkName can not be null!");
|
||||
JudgesNull(ids, "ids can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(pkName, ids)
|
||||
.build();
|
||||
int i = tableMapper.updateByWhere(data, tableName, condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int updateInPk(OsSysTable osSysTable, List<E> ids, Map<String, Object> data) {
|
||||
JudgesNull(data, "data can not be null!");
|
||||
JudgesNull(osSysTable.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(osSysTable.getTablePk(), "pkName can not be null!");
|
||||
JudgesNull(ids, "ids can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(osSysTable.getTablePk(), ids)
|
||||
.build();
|
||||
int i = tableMapper.updateByWhere(data, osSysTable.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public <E> int updateByCondition(DataMap<E> dataMap, Condition condition) {
|
||||
JudgesNull(dataMap.getData(), "data can not be null!");
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
int i = tableMapper.updateByWhere(dataMap.getData(), dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int updateByCondition(String tableName, Map<String, Object> data, Condition condition) {
|
||||
JudgesNull(data, "data can not be null!");
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
int i = tableMapper.updateByWhere(data, tableName, condition.getSql());
|
||||
SqlException.base(i, "更新失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int deleteByPk(DataMap<E> dataMap) {
|
||||
JudgesNull(dataMap.getPkValue(), "pkValue can not be null!");
|
||||
JudgesNull(dataMap.getPkName(), "pkName can not be null!");
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andEqual(dataMap.getPkName(), dataMap.getPkValue())
|
||||
.build();
|
||||
int i = tableMapper.deleteByWhere(dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByPk(String tableName, String pkName, Object pkValue) {
|
||||
JudgesNull(pkValue, "pkValue can not be null!");
|
||||
JudgesNull(pkName, "pkName can not be null!");
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andEqual(pkName, pkValue)
|
||||
.build();
|
||||
int i = tableMapper.deleteByWhere(tableName, condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByPk(OsSysTable osSysTable, Object pkValue) {
|
||||
JudgesNull(pkValue, "pkValue can not be null!");
|
||||
JudgesNull(osSysTable.getTablePk(), "pkName can not be null!");
|
||||
JudgesNull(osSysTable.getTableName(), "tableName can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andEqual(osSysTable.getTablePk(), pkValue)
|
||||
.build();
|
||||
int i = tableMapper.deleteByWhere(osSysTable.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int deleteInPk(String tableName, String pkName, List<E> ids) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
JudgesNull(pkName, "pkName can not be null!");
|
||||
JudgesNull(ids, "ids can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(pkName, ids)
|
||||
.build();
|
||||
int i = tableMapper.deleteByWhere(tableName, condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int deleteInPk(DataMap<E> dataMap) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(dataMap.getPkName(), "pkName can not be null!");
|
||||
JudgesNull(dataMap.getIds(), "ids can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(dataMap.getPkName(), dataMap.getIdList())
|
||||
.build();
|
||||
int i = tableMapper.deleteByWhere(dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int deleteInPk(OsSysTable osSysTable, List<E> ids) {
|
||||
JudgesNull(osSysTable.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(osSysTable.getTablePk(), "pkName can not be null!");
|
||||
JudgesNull(ids, "ids can not be null!");
|
||||
Condition condition = Condition.creatCriteria()
|
||||
.andIn(osSysTable.getTablePk(), ids)
|
||||
.build();
|
||||
int i = tableMapper.deleteByWhere(osSysTable.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> int deleteByCondition(DataMap<E> dataMap, Condition condition) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
int i = tableMapper.deleteByWhere(dataMap.getTableName(), condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByCondition(String tableName, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
int i = tableMapper.deleteByWhere(tableName, condition.getSql());
|
||||
SqlException.base(i, "删除失败");
|
||||
return i;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectAll(String tableName) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.useSql(SelectCondition.builder().tableName(tableName).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> List<Map<String, Object>> selectByEqual(DataMap<E> dataMap, Map<String, Object> map) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
Condition condition = equal(dataMap, map);
|
||||
return tableMapper.useSql(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectByEqual(String tableName, Map<String, Object> map) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
Condition condition = equal(DataMap.builder().tableName(tableName).build(), map);
|
||||
return tableMapper.useSql(condition.getSql());
|
||||
}
|
||||
|
||||
|
||||
private <E> Condition equal(DataMap<E> dataMap, Map<String, Object> map) {
|
||||
Condition condition = Condition.creatCriteria(dataMap).build();
|
||||
if (map != null && !map.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
condition = condition
|
||||
.toCreatCriteria()
|
||||
.andEqual(entry.getKey(), entry.getValue())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
return condition;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> PageInfo<Map<String, Object>> selectByEqual(DataMap<E> dataMap, Map<String, Object> map, WebPageInfo webPageInfo) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
MyPageHelper.start(webPageInfo);
|
||||
Condition condition = equal(dataMap, map);
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> selectByEqual(String tableName, Map<String, Object> map, WebPageInfo webPageInfo) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
MyPageHelper.start(webPageInfo);
|
||||
Condition condition = equal(DataMap.builder().tableName(tableName).build(), map);
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> Map<String, Object> selectOneByEqual(DataMap<E> dataMap, Map<String, Object> map) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
Condition condition = equal(dataMap, map);
|
||||
return tableMapper.userSqlByOne(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> Map<String, Object> selectByPk(DataMap<E> dataMap) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(dataMap.getPkName(), "pkName can not be null!");
|
||||
JudgesNull(dataMap.getPkValue(), "pkValue can not be null!");
|
||||
Condition condition = Condition.creatCriteria(dataMap).build();
|
||||
condition = condition.toCreatCriteria().andEqual(dataMap.getPkName(), dataMap.getPkValue()).build();
|
||||
return tableMapper.userSqlByOne(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectByPk(OsSysTable osSysTable, Object pkValue) {
|
||||
JudgesNull(osSysTable.getTableName(), "tableName can not be null!");
|
||||
JudgesNull(osSysTable.getTablePk(), "pkName can not be null!");
|
||||
JudgesNull(pkValue, "pkValue can not be null!");
|
||||
Condition condition = Condition.creatCriteria(DataMap.builder().sysOsTable(osSysTable).pkValue(pkValue).build()).build();
|
||||
condition = condition.toCreatCriteria().andEqual(osSysTable.getTablePk(), pkValue).build();
|
||||
return tableMapper.userSqlByOne(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectByPk(String tableName, String pkName, Object pkValue) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
JudgesNull(pkName, "pkName can not be null!");
|
||||
JudgesNull(pkValue, "pkValue can not be null!");
|
||||
Condition condition = Condition.creatCriteria(DataMap.builder().tableName(tableName).pkName(pkName).pkValue(pkValue).build()).build();
|
||||
condition = condition.toCreatCriteria().andEqual(pkName, pkValue).build();
|
||||
return tableMapper.userSqlByOne(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectByCondition(Condition condition) {
|
||||
return tableMapper.useSql(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> List<Map<String, Object>> selectByCondition(DataMap<E> dataMap, Condition condition) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
return tableMapper.useSql(condition.toCreatCriteria(dataMap).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectByCondition(String tableName, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.useSql(condition.toCreatCriteria(DataMap.builder().tableName(tableName).build()).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectByCondition(String tableName, List<String> fieldList, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.useSql(condition
|
||||
.toCreatCriteria(DataMap.builder().tableName(tableName).fieldList(fieldList).build())
|
||||
.build()
|
||||
.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectByCondition(String tableName, String fieldList, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.useSql(condition
|
||||
.toCreatCriteria(DataMap.builder().tableName(tableName).fields(fieldList).build())
|
||||
.build()
|
||||
.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> selectByCondition(Condition condition, WebPageInfo webPageInfo) {
|
||||
MyPageHelper.start(webPageInfo);
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> PageInfo<Map<String, Object>> selectByCondition(DataMap<E> dataMap, Condition condition, WebPageInfo webPageInfo) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
MyPageHelper.start(webPageInfo);
|
||||
condition = condition.toCreatCriteria(dataMap).build();
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> selectByCondition(String tableName, Condition condition, WebPageInfo webPageInfo) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
MyPageHelper.start(webPageInfo);
|
||||
condition = condition.toCreatCriteria(DataMap.builder().tableName(tableName).build()).build();
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> selectByCondition(String tableName, List<String> fieldList, Condition condition, WebPageInfo webPageInfo) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
MyPageHelper.start(webPageInfo);
|
||||
condition = condition.toCreatCriteria(DataMap.builder().tableName(tableName).fieldList(fieldList).build()).build();
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> selectByCondition(String tableName, String fieldList, Condition condition, WebPageInfo webPageInfo) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
MyPageHelper.start(webPageInfo);
|
||||
condition = condition.toCreatCriteria(DataMap.builder().tableName(tableName).fields(fieldList).build()).build();
|
||||
return new PageInfo<>(tableMapper.useSql(condition.getSql()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E> Map<String, Object> selectOneByCondition(DataMap<E> dataMap, Condition condition) {
|
||||
JudgesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
return tableMapper.userSqlByOne(condition.toCreatCriteria(dataMap).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectOneByCondition(String tableName, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.userSqlByOne(condition.toCreatCriteria(DataMap.builder().tableName(tableName).build()).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectOneByCondition(String tableName, List<String> fieldList, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.userSqlByOne(condition.toCreatCriteria(DataMap.builder().tableName(tableName).fieldList(fieldList).build()).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectOneByCondition(String tableName, String fieldList, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
return tableMapper.userSqlByOne(condition.toCreatCriteria(DataMap.builder().tableName(tableName).fields(fieldList).build()).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectOneByCondition(Condition condition) {
|
||||
return tableMapper.userSqlByOne(condition.getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectJoinByCondition(String tableName, JoinCondition joinCondition, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
SelectCondition selectJoinBuilder = SelectCondition
|
||||
.joinBuilder(tableName)
|
||||
.join(joinCondition).build();
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectJoinBuilder).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectJoinByCondition(String tableName, List<JoinCondition> joinCondition, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
SelectCondition selectJoinBuilder = SelectCondition
|
||||
.joinBuilder(tableName)
|
||||
.join(joinCondition).build();
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectJoinBuilder).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectLeftJoinByCondition(String tableName, JoinCondition joinCondition, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
SelectCondition selectJoinBuilder = SelectCondition
|
||||
.joinBuilder(tableName)
|
||||
.leftJoin(joinCondition).build();
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectJoinBuilder).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectLeftJoinByCondition(String tableName, List<JoinCondition> joinCondition, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
SelectCondition selectJoinBuilder = SelectCondition
|
||||
.joinBuilder(tableName)
|
||||
.leftJoin(joinCondition).build();
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectJoinBuilder).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectRightJoinByCondition(String tableName, JoinCondition joinCondition, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
SelectCondition selectJoinBuilder = SelectCondition
|
||||
.joinBuilder(tableName)
|
||||
.rightJoin(joinCondition).build();
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectJoinBuilder).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectRightJoinByCondition(String tableName, List<JoinCondition> joinCondition, Condition condition) {
|
||||
JudgesNull(tableName, "tableName can not be null!");
|
||||
SelectCondition selectJoinBuilder = SelectCondition
|
||||
.joinBuilder(tableName)
|
||||
.rightJoin(joinCondition).build();
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectJoinBuilder).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectionByCondition(SelectCondition selectCondition, Condition condition) {
|
||||
return tableMapper.useSql(condition.toCreatCriteria(selectCondition).build().getSql());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectSql(String sql) {
|
||||
return tableMapper.useSql(sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> selectSqlByPage(String sql, WebPageInfo webPageInfo) {
|
||||
MyPageHelper.start(webPageInfo);
|
||||
return new PageInfo<>(tableMapper.useSql(sql));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> selectOneSql(String sql) {
|
||||
return tableMapper.userSqlByOne(sql);
|
||||
}
|
||||
|
||||
public void JudgesNull(Object object, String str) {
|
||||
if (object == null) {
|
||||
throw new BaseMapperException(str);
|
||||
}
|
||||
}
|
||||
|
||||
private Object getSequence(String tableName, String pkName) {
|
||||
Object id;
|
||||
try {
|
||||
id = tableMapper.getSequence(tableName);
|
||||
} catch (Exception e) {
|
||||
MyPageHelper.start(WebPageInfo.builder().pageNum(1).pageSize(1).order(WebPageInfo.DESC).sortField(pkName).build());
|
||||
DataMap<Object> dataMap = DataMap.builder().tableName(tableName).pkName(pkName).fields(pkName).build();
|
||||
Condition condition = Condition.creatCriteria(dataMap).build();
|
||||
Map<String, Object> map = selectOneByCondition(condition);
|
||||
tableMapper.createSequence(tableName, map.get(pkName));
|
||||
id = tableMapper.getSequence(tableName);
|
||||
}
|
||||
return Long.parseLong(id.toString())+1L;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.utils.XssClass;
|
||||
import com.hcframe.base.common.utils.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @decription 生成where条件sqlApi
|
||||
* @date 2020-12-22
|
||||
*/
|
||||
public class Condition implements Serializable {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(Condition.class);
|
||||
|
||||
private static final long serialVersionUID = -1097188960881519597L;
|
||||
public static String L_CURVES = "(";
|
||||
public static String R_CURVES = ")";
|
||||
public static String EQUAL = "=";
|
||||
public static String WHERE = "WHERE";
|
||||
public static String OneEq = "1=1";
|
||||
public static String LIKE = "LIKE";
|
||||
public static String IN = "IN";
|
||||
public static String AND = "AND";
|
||||
public static String OR = "OR";
|
||||
public static String BETWEEN = "BETWEEN";
|
||||
public static String LT = "<";
|
||||
public static String GT = ">";
|
||||
public static String LTE = "<=";
|
||||
public static String GTE = ">=";
|
||||
public static String GROUP_BY = "GROUP BY";
|
||||
|
||||
private String sql = "";
|
||||
|
||||
private String selecSql = "";
|
||||
|
||||
private String conditionSql = "";
|
||||
|
||||
private SelectCondition selectCondition;
|
||||
|
||||
public Condition() {
|
||||
}
|
||||
|
||||
public Condition(String sql,SelectCondition selectCondition) {
|
||||
this.selectCondition = selectCondition;
|
||||
this.sql = sql;
|
||||
String[] sqlArr;
|
||||
if (sql.contains(" WHERE ")) {
|
||||
sqlArr = sql.split(WHERE + " " + OneEq);
|
||||
this.selecSql = sqlArr[0];
|
||||
this.conditionSql = sqlArr[1];
|
||||
} else if (sql.contains(" where ")) {
|
||||
sqlArr = sql.split(" where ");
|
||||
this.selecSql = sqlArr[0];
|
||||
this.conditionSql = sqlArr[1];
|
||||
} else {
|
||||
this.selecSql = sql;
|
||||
}
|
||||
}
|
||||
|
||||
public SelectCondition getSelectCondition() {
|
||||
return selectCondition;
|
||||
}
|
||||
|
||||
public void setSelectCondition(SelectCondition selectCondition) {
|
||||
this.selectCondition = selectCondition;
|
||||
}
|
||||
|
||||
public String getSelecSql() {
|
||||
return selecSql;
|
||||
}
|
||||
|
||||
public void setSelecSql(String selecSql) {
|
||||
this.selecSql = selecSql;
|
||||
}
|
||||
|
||||
public String getConditionSql() {
|
||||
return conditionSql;
|
||||
}
|
||||
|
||||
public void setConditionSql(String conditionSql) {
|
||||
this.conditionSql = conditionSql;
|
||||
}
|
||||
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public void setSql(String sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public static void JudesNull(Object object, String str) {
|
||||
if (object == null) {
|
||||
throw new ServiceException(str);
|
||||
}
|
||||
}
|
||||
|
||||
public static ConditionBuilder creatCriteria() {
|
||||
return new ConditionBuilder();
|
||||
}
|
||||
|
||||
public static ConditionBuilder creatCriteria(SelectCondition selectCondition) {
|
||||
return new ConditionBuilder(selectCondition);
|
||||
}
|
||||
|
||||
public static ConditionBuilder creatCriteria(SelectCondition selectCondition, boolean flag) {
|
||||
return new ConditionBuilder(selectCondition, flag);
|
||||
}
|
||||
|
||||
public static ConditionBuilder creatCriteria(DataMap dataMap) {
|
||||
JudesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
return new ConditionBuilder(dataMap.getSelectCondition());
|
||||
}
|
||||
|
||||
public static ConditionBuilder creatCriteria(DataMap dataMap, boolean flag) {
|
||||
JudesNull(dataMap.getTableName(), "tableName can not be null!");
|
||||
return new ConditionBuilder(dataMap.getSelectCondition(), flag);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否开启防注入
|
||||
*
|
||||
* @param flag 默认开启
|
||||
* @return
|
||||
*/
|
||||
public static ConditionBuilder creatCriteria(boolean flag) {
|
||||
return new ConditionBuilder();
|
||||
}
|
||||
|
||||
public ConditionBuilder toCreatCriteria() {
|
||||
return new ConditionBuilder(this.sql);
|
||||
}
|
||||
public ConditionBuilder toCreatCriteria(SelectCondition selectCondition) {
|
||||
return new ConditionBuilder(selectCondition,this.sql);
|
||||
}
|
||||
|
||||
public ConditionBuilder toCreatCriteria(DataMap dataMap) {
|
||||
return new ConditionBuilder(dataMap.getSelectCondition(),this.sql);
|
||||
}
|
||||
|
||||
public static class ConditionBuilder {
|
||||
|
||||
private String sql = "";
|
||||
|
||||
private String selecSql = "";
|
||||
|
||||
private String conditionSql = "";
|
||||
|
||||
private int lrn = 0;
|
||||
|
||||
private int rrn = 0;
|
||||
|
||||
// 是否开启防注入,默认开启
|
||||
private boolean flag = true;
|
||||
|
||||
private SelectCondition selectCondition;
|
||||
|
||||
public String getSelecSql() {
|
||||
return selecSql;
|
||||
}
|
||||
|
||||
public void setSelecSql(String selecSql) {
|
||||
this.selecSql = selecSql;
|
||||
}
|
||||
|
||||
public String getConditionSql() {
|
||||
return conditionSql;
|
||||
}
|
||||
|
||||
public void setConditionSql(String conditionSql) {
|
||||
this.conditionSql = conditionSql;
|
||||
}
|
||||
|
||||
public ConditionBuilder() {
|
||||
}
|
||||
|
||||
public ConditionBuilder(boolean flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
|
||||
public ConditionBuilder(SelectCondition selectCondition) {
|
||||
this.selectCondition = selectCondition;
|
||||
this.selecSql = selectCondition.getSql();
|
||||
}
|
||||
|
||||
public ConditionBuilder(SelectCondition selectCondition, boolean flag) {
|
||||
this.flag = flag;
|
||||
this.selectCondition = selectCondition;
|
||||
this.selecSql = selectCondition.getSql();
|
||||
}
|
||||
|
||||
public ConditionBuilder(SelectCondition selectCondition,String sql) {
|
||||
spliteSql(sql);
|
||||
this.selectCondition = selectCondition;
|
||||
this.selecSql = selectCondition.getSql();
|
||||
}
|
||||
|
||||
private void spliteSql(String sql) {
|
||||
String[] sqlArr;
|
||||
if (sql.contains(" WHERE ")) {
|
||||
sqlArr = sql.split(WHERE + " " + OneEq);
|
||||
this.selecSql = sqlArr[0];
|
||||
this.conditionSql = sqlArr[1];
|
||||
} else if (sql.contains(" where ")) {
|
||||
sqlArr = sql.split(" where ");
|
||||
this.selecSql = sqlArr[0];
|
||||
this.conditionSql = sqlArr[1];
|
||||
} else {
|
||||
this.selecSql = sql;
|
||||
}
|
||||
}
|
||||
|
||||
public ConditionBuilder(SelectCondition selectCondition,String sql,boolean flag) {
|
||||
this.flag = flag;
|
||||
spliteSql(sql);
|
||||
this.selectCondition = selectCondition;
|
||||
this.selecSql = selectCondition.getSql();
|
||||
}
|
||||
|
||||
public ConditionBuilder(String sql) {
|
||||
this.sql = sql;
|
||||
spliteSql(sql);
|
||||
}
|
||||
|
||||
public ConditionBuilder leftCurves() {
|
||||
this.conditionSql += L_CURVES + " ";
|
||||
this.lrn++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder rightCurves() {
|
||||
this.conditionSql += " " + R_CURVES + " ";
|
||||
this.rrn++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder and() {
|
||||
this.conditionSql += " " + AND + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder or() {
|
||||
this.conditionSql += " " + OR + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder equal(String key, Object value) {
|
||||
sqlCheck(value);
|
||||
this.conditionSql += " " + key + EQUAL + "'" + value + "'";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andEqual(String key, Object value) {
|
||||
this.and().equal(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orEqual(String key, Object value) {
|
||||
this.or().equal(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder like(String key, Object value) {
|
||||
sqlCheck(value);
|
||||
this.conditionSql += " " + key + " " + LIKE + " '%" + value + "%'";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andLike(String key, Object value) {
|
||||
this.and().like(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orLike(String key, Object value) {
|
||||
this.or().like(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public <E> ConditionBuilder in(String key, List<E> value) {
|
||||
StringBuilder inStr = new StringBuilder(L_CURVES);
|
||||
int i = 1;
|
||||
for (Object object : value) {
|
||||
sqlCheck(object);
|
||||
inStr.append("'").append(object.toString()).append("'");
|
||||
if (i != value.size()) {
|
||||
inStr.append(",");
|
||||
}
|
||||
i++;
|
||||
}
|
||||
inStr.append(R_CURVES);
|
||||
this.conditionSql += " " + key + " " + IN + " " + inStr.toString();
|
||||
return this;
|
||||
}
|
||||
|
||||
public <E> ConditionBuilder andIn(String key, List<E> value) {
|
||||
this.and().in(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public <E> ConditionBuilder orIn(String key, List<E> value) {
|
||||
this.or().in(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder between(String key, Object start, Object end) {
|
||||
sqlCheck(start);
|
||||
sqlCheck(end);
|
||||
this.conditionSql += " " + key + " " + BETWEEN + " '" + start.toString() + "' " + AND + " '" + end.toString() + "' ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andBetween(String key, Object start, Object end) {
|
||||
this.and().between(key, start, end);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orBetween(String key, Object start, Object end) {
|
||||
this.or().between(key, start, end);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder lt(String key, Object value) {
|
||||
sqlCheck(value);
|
||||
this.conditionSql += " " + key + " " + LT + " '" + value.toString() + "' ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andLt(String key, Object value) {
|
||||
this.and().lt(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orLt(String key, Object value) {
|
||||
this.or().lt(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder gt(String key, Object value) {
|
||||
sqlCheck(value);
|
||||
this.conditionSql += " " + key + " " + GT + " '" + value.toString() + "' ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andGt(String key, Object value) {
|
||||
this.and().gt(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orGt(String key, Object value) {
|
||||
this.or().gt(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder lte(String key, Object value) {
|
||||
sqlCheck(value);
|
||||
this.conditionSql += " " + key + " " + LTE + " '" + value.toString() + "' ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andLte(String key, Object value) {
|
||||
this.and().lte(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orLte(String key, Object value) {
|
||||
this.or().lte(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder gte(String key, Object value) {
|
||||
sqlCheck(value);
|
||||
this.conditionSql += " " + key + " " + GTE + " '" + value.toString() + "' ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder andGte(String key, Object value) {
|
||||
this.and().gte(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder orGte(String key, Object value) {
|
||||
this.or().gte(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ConditionBuilder groupBy(String ...str) {
|
||||
int i = 1;
|
||||
StringBuilder stringBuilder = new StringBuilder(" " + GROUP_BY + " ");
|
||||
for (String s : str) {
|
||||
stringBuilder.append(s);
|
||||
if (i != str.length) {
|
||||
stringBuilder.append(",");
|
||||
}
|
||||
i++;
|
||||
}
|
||||
this.conditionSql += stringBuilder.toString();
|
||||
return this;
|
||||
}
|
||||
|
||||
public void sqlCheck(Object obj) {
|
||||
if (this.flag) {
|
||||
if (XssClass.sqlInj(obj.toString())) {
|
||||
logger.error("非法字符:"+obj.toString());
|
||||
throw new ServiceException("value中含有非法字符,有注入风险!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Condition build() {
|
||||
if (this.rrn != this.lrn) {
|
||||
logger.error("sql语法错误,请检查小括号是否都闭合");
|
||||
logger.error("SQL语句:" + this.sql);
|
||||
throw new ServiceException("sql语法错误,请检查小括号是否都闭合");
|
||||
}
|
||||
this.sql = this.selecSql + " " + WHERE + " " + OneEq + " " + this.conditionSql;
|
||||
if (StringUtils.isEmpty(this.selecSql)) {
|
||||
this.sql = " " + WHERE + " " + OneEq + " " + this.conditionSql;
|
||||
}
|
||||
if (StringUtils.isEmpty(this.conditionSql)) {
|
||||
this.sql = this.selecSql;
|
||||
}
|
||||
return new Condition(this.sql,this.selectCondition);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import com.hcframe.base.common.utils.ObjectUtil;
|
||||
import com.hcframe.base.module.shiro.FtToken;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-23
|
||||
* @decription 数据库dataMap泛型
|
||||
*/
|
||||
public class DataMap<T> implements Serializable {
|
||||
private static final long serialVersionUID = -931903976665708139L;
|
||||
public static final String VERSION = "VERSION";
|
||||
private Map<String, Object> data = new HashMap();
|
||||
private String ids;
|
||||
private List<String> idList;
|
||||
private String tableName;
|
||||
private String pkName;
|
||||
private Object pkValue;
|
||||
private String fields = "*";
|
||||
private List<String> fieldList;
|
||||
private String subData;
|
||||
private String selectSql;
|
||||
private SelectCondition selectCondition;
|
||||
private T obj;
|
||||
|
||||
public T getObj() {
|
||||
return obj;
|
||||
}
|
||||
|
||||
public void set(String key, Object value) {
|
||||
ObjectUtil.setField(this.obj, key, value);
|
||||
}
|
||||
|
||||
public void setObj(T obj) {
|
||||
this.obj = obj;
|
||||
ObjectUtil.objToSqlMap(obj, this);
|
||||
}
|
||||
|
||||
public DataMap(OsSysTable osSysTable) {
|
||||
this.pkName = osSysTable.getTablePk();
|
||||
this.tableName = osSysTable.getTableName();
|
||||
}
|
||||
|
||||
public List<String> getIdList() {
|
||||
if (this.idList == null) {
|
||||
String[] strArr = this.ids.split(",");
|
||||
this.idList = Arrays.asList(strArr);
|
||||
}
|
||||
return this.idList;
|
||||
}
|
||||
|
||||
public List<String> getFieldList() {
|
||||
if (this.fieldList == null) {
|
||||
String[] strArr = this.fields.split(",");
|
||||
this.fieldList = Arrays.asList(strArr);
|
||||
}
|
||||
return this.fieldList;
|
||||
}
|
||||
|
||||
public String getSelectSql() {
|
||||
SelectCondition selectCondition = SelectCondition.builder()
|
||||
.tableName(this.tableName)
|
||||
.field(this.getFieldList())
|
||||
.build();
|
||||
this.selectSql = selectCondition.getSql();
|
||||
return this.selectSql;
|
||||
}
|
||||
|
||||
public SelectCondition getSelectCondition() {
|
||||
return SelectCondition.builder().tableName(this.tableName).field(this.getFieldList()).build();
|
||||
}
|
||||
|
||||
public static <T> DataMapBuilder<T> builder() {
|
||||
return new DataMapBuilder<T>();
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> toBuilder() {
|
||||
return (new DataMapBuilder<T>()).data(this.data).ids(this.ids).idList(this.idList).tableName(this.tableName).pkName(this.pkName).pkValue(this.pkValue).fields(this.fields).fieldList(this.fieldList).subData(this.subData).selectSql(this.selectSql).selectCondition(this.selectCondition);
|
||||
}
|
||||
|
||||
public Object get(String key) {
|
||||
return this.data.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (o == this) {
|
||||
return true;
|
||||
} else if (!(o instanceof DataMap)) {
|
||||
return false;
|
||||
} else {
|
||||
DataMap other = (DataMap) o;
|
||||
if (!other.canEqual(this)) {
|
||||
return false;
|
||||
} else {
|
||||
label143:
|
||||
{
|
||||
Object this$data = this.getData();
|
||||
Object other$data = other.getData();
|
||||
if (this$data == null) {
|
||||
if (other$data == null) {
|
||||
break label143;
|
||||
}
|
||||
} else if (this$data.equals(other$data)) {
|
||||
break label143;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Object this$ids = this.getIds();
|
||||
Object other$ids = other.getIds();
|
||||
if (this$ids == null) {
|
||||
if (other$ids != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!this$ids.equals(other$ids)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Object this$idList = this.getIdList();
|
||||
Object other$idList = other.getIdList();
|
||||
if (this$idList == null) {
|
||||
if (other$idList != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!this$idList.equals(other$idList)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
label122:
|
||||
{
|
||||
Object this$tableName = this.getTableName();
|
||||
Object other$tableName = other.getTableName();
|
||||
if (this$tableName == null) {
|
||||
if (other$tableName == null) {
|
||||
break label122;
|
||||
}
|
||||
} else if (this$tableName.equals(other$tableName)) {
|
||||
break label122;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
label115:
|
||||
{
|
||||
Object this$pkName = this.getPkName();
|
||||
Object other$pkName = other.getPkName();
|
||||
if (this$pkName == null) {
|
||||
if (other$pkName == null) {
|
||||
break label115;
|
||||
}
|
||||
} else if (this$pkName.equals(other$pkName)) {
|
||||
break label115;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Object this$pkValue = this.getPkValue();
|
||||
Object other$pkValue = other.getPkValue();
|
||||
if (this$pkValue == null) {
|
||||
if (other$pkValue != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!this$pkValue.equals(other$pkValue)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Object this$fields = this.getFields();
|
||||
Object other$fields = other.getFields();
|
||||
if (this$fields == null) {
|
||||
if (other$fields != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!this$fields.equals(other$fields)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
label94:
|
||||
{
|
||||
Object this$fieldList = this.getFieldList();
|
||||
Object other$fieldList = other.getFieldList();
|
||||
if (this$fieldList == null) {
|
||||
if (other$fieldList == null) {
|
||||
break label94;
|
||||
}
|
||||
} else if (this$fieldList.equals(other$fieldList)) {
|
||||
break label94;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
label87:
|
||||
{
|
||||
Object this$subData = this.getSubData();
|
||||
Object other$subData = other.getSubData();
|
||||
if (this$subData == null) {
|
||||
if (other$subData == null) {
|
||||
break label87;
|
||||
}
|
||||
} else if (this$subData.equals(other$subData)) {
|
||||
break label87;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Object this$selectSql = this.getSelectSql();
|
||||
Object other$selectSql = other.getSelectSql();
|
||||
if (this$selectSql == null) {
|
||||
if (other$selectSql != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!this$selectSql.equals(other$selectSql)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Object this$selectCondition = this.getSelectCondition();
|
||||
Object other$selectCondition = other.getSelectCondition();
|
||||
if (this$selectCondition == null) {
|
||||
if (other$selectCondition != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!this$selectCondition.equals(other$selectCondition)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean canEqual(final Object other) {
|
||||
return other instanceof DataMap;
|
||||
}
|
||||
|
||||
|
||||
public DataMap() {
|
||||
}
|
||||
|
||||
public DataMap(final Map<String, Object> data, final String ids, final List<String> idList, final String tableName, final String pkName, final Object pkValue, final String fields, final List<String> fieldList, final String subData, final String selectSql, final SelectCondition selectCondition, final T obj) {
|
||||
this.data = data;
|
||||
this.ids = ids;
|
||||
this.idList = idList;
|
||||
this.tableName = tableName;
|
||||
this.pkName = pkName;
|
||||
this.pkValue = pkValue;
|
||||
this.fields = fields;
|
||||
this.fieldList = fieldList;
|
||||
this.subData = subData;
|
||||
this.selectSql = selectSql;
|
||||
this.selectCondition = selectCondition;
|
||||
this.obj = obj;
|
||||
}
|
||||
|
||||
public Map<String, Object> getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
public String getIds() {
|
||||
return this.ids;
|
||||
}
|
||||
|
||||
public String getTableName() {
|
||||
return this.tableName;
|
||||
}
|
||||
|
||||
public String getPkName() {
|
||||
return this.pkName;
|
||||
}
|
||||
|
||||
public Object getPkValue() {
|
||||
return this.pkValue;
|
||||
}
|
||||
|
||||
public String getFields() {
|
||||
return this.fields;
|
||||
}
|
||||
|
||||
public String getSubData() {
|
||||
return this.subData;
|
||||
}
|
||||
|
||||
public void setData(final Map<String, Object> data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public void setIds(final String ids) {
|
||||
this.ids = ids;
|
||||
}
|
||||
|
||||
public void setIdList(final List<String> idList) {
|
||||
this.idList = idList;
|
||||
}
|
||||
|
||||
public void setTableName(final String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public void setPkName(final String pkName) {
|
||||
this.pkName = pkName;
|
||||
}
|
||||
|
||||
public void setPkValue(final Object pkValue) {
|
||||
this.pkValue = pkValue;
|
||||
}
|
||||
|
||||
public void setFields(final String fields) {
|
||||
this.fields = fields;
|
||||
}
|
||||
|
||||
public void setFieldList(final List<String> fieldList) {
|
||||
this.fieldList = fieldList;
|
||||
}
|
||||
|
||||
public void setSubData(final String subData) {
|
||||
this.subData = subData;
|
||||
}
|
||||
|
||||
public void setSelectSql(final String selectSql) {
|
||||
this.selectSql = selectSql;
|
||||
}
|
||||
|
||||
public void setSelectCondition(final SelectCondition selectCondition) {
|
||||
this.selectCondition = selectCondition;
|
||||
}
|
||||
|
||||
|
||||
public static class DataMapBuilder<T> {
|
||||
private Map<String, Object> data = new HashMap<>();
|
||||
private String ids;
|
||||
private List<String> idList;
|
||||
private String tableName;
|
||||
private String pkName;
|
||||
private Object pkValue;
|
||||
private String fields = "*";
|
||||
private List<String> fieldList;
|
||||
private String subData;
|
||||
private String selectSql;
|
||||
private SelectCondition selectCondition;
|
||||
private T obj;
|
||||
|
||||
DataMapBuilder() {
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> obj(T object) {
|
||||
this.obj = object;
|
||||
ObjectUtil.objToSqlMap(object, this);
|
||||
return this;
|
||||
}
|
||||
|
||||
public <E> DataMapBuilder<T> set(String key, Object value) {
|
||||
ObjectUtil.setField(this.obj, key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> add(String key, Object value) {
|
||||
this.data.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Object get(String key) {
|
||||
return this.data.get(key);
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> remove(String key) {
|
||||
this.data.remove(key);
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> remove(String key, Object value) {
|
||||
this.data.remove(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> data(final Map<String, Object> data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> ids(final String ids) {
|
||||
this.ids = ids;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> idList(final List<String> idList) {
|
||||
this.idList = idList;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> tableName(final String tableName) {
|
||||
this.tableName = tableName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> pkName(final String pkName) {
|
||||
this.pkName = pkName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> pkValue(final Object pkValue) {
|
||||
this.pkValue = pkValue;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> fields(final String fields) {
|
||||
this.fields = fields;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> sysOsTable(OsSysTable table) {
|
||||
this.pkName = table.getTablePk();
|
||||
this.tableName = table.getTableName();
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> fieldList(final List<String> fieldList) {
|
||||
this.fieldList = fieldList;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> subData(final String subData) {
|
||||
this.subData = subData;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> selectSql(final String selectSql) {
|
||||
this.selectSql = selectSql;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMapBuilder<T> selectCondition(final SelectCondition selectCondition) {
|
||||
this.selectCondition = selectCondition;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataMap<T> build() {
|
||||
return new DataMap<>(this.data, this.ids, this.idList, this.tableName, this.pkName, this.pkValue, this.fields, this.fieldList, this.subData, this.selectSql, this.selectCondition, this.obj);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Long l = 1L;
|
||||
FtToken ftToken = new FtToken();
|
||||
DataMap<FtToken> dataMap = DataMap.<FtToken>builder().obj(ftToken).build();
|
||||
System.out.println(dataMap.getSelectSql());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @decription 前端关联查询格式
|
||||
* @date 2020-12-25
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
public class JoinCondition {
|
||||
// 表名
|
||||
private String name;
|
||||
// 关联查询字段
|
||||
private String field;
|
||||
// 与左表关联查询字段
|
||||
private String joinField;
|
||||
// 关联的父表
|
||||
private String fkTable;
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.utils.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-23
|
||||
* @decription select语句拼装工具类
|
||||
*/
|
||||
@Component
|
||||
public class SelectCondition implements Serializable {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(SelectCondition.class);
|
||||
private static final long serialVersionUID = 4068737478156616795L;
|
||||
|
||||
private static String SELECT = "SELECT";
|
||||
private static String FROM = "FROM";
|
||||
|
||||
private String sql = "";
|
||||
|
||||
private String tableName = "";
|
||||
|
||||
public SelectCondition() {
|
||||
}
|
||||
|
||||
public SelectCondition(String sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public SelectCondition(String sql, String tableName) {
|
||||
this.sql = sql;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public void setSql(String sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public static SelectBuilder builder() {
|
||||
return new SelectBuilder();
|
||||
}
|
||||
|
||||
public SelectBuilder toBuilder() {
|
||||
return new SelectBuilder(this.sql);
|
||||
}
|
||||
|
||||
public static SelectJoinBuilder joinBuilder(String tableName) {
|
||||
return new SelectJoinBuilder(tableName);
|
||||
}
|
||||
|
||||
public SelectJoinBuilder toJoinBuilder() {
|
||||
return new SelectJoinBuilder(this.sql, this.tableName);
|
||||
}
|
||||
|
||||
public static SelectSqlJoinBuilder sqlJoinBuilder(String tableName) {
|
||||
return new SelectSqlJoinBuilder(tableName);
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder toSqlJoinBuilder() {
|
||||
return new SelectSqlJoinBuilder(this.sql, this.tableName);
|
||||
}
|
||||
|
||||
|
||||
private static String getFieldStr(List<String> fieldList) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
if (fieldList != null && fieldList.size() > 0) {
|
||||
int i = 1;
|
||||
for (String field : fieldList) {
|
||||
stringBuilder.append(field);
|
||||
if (i != fieldList.size()) {
|
||||
stringBuilder.append(",");
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
} else {
|
||||
return " * ";
|
||||
}
|
||||
}
|
||||
|
||||
public static class SelectBuilder {
|
||||
private String sql = "";
|
||||
|
||||
private List<String> fieldList = new LinkedList<>();
|
||||
|
||||
private String tableName;
|
||||
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
public void setTableName(String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public SelectBuilder() {
|
||||
}
|
||||
|
||||
public SelectBuilder(String sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public SelectBuilder tableName(String tableName) {
|
||||
this.tableName = tableName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectBuilder field(String field) {
|
||||
this.fieldList.add(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectBuilder field(List<String> field) {
|
||||
this.fieldList.addAll(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectCondition build() {
|
||||
if (StringUtils.isEmpty(this.tableName)) {
|
||||
throw new ServiceException("表名不能为空");
|
||||
}
|
||||
this.sql = SELECT + " ";
|
||||
this.sql += getFieldStr(this.fieldList);
|
||||
this.sql += " " + FROM + " " + this.tableName;
|
||||
return new SelectCondition(this.sql);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SelectJoinBuilder {
|
||||
private String sql = "";
|
||||
|
||||
private String tableName;
|
||||
|
||||
private List<String> fieldList = new LinkedList<>();
|
||||
|
||||
private List<JoinCondition> joinConditions = new LinkedList<>();
|
||||
|
||||
private List<JoinCondition> leftConditions = new LinkedList<>();
|
||||
|
||||
private List<JoinCondition> rightConditions = new LinkedList<>();
|
||||
|
||||
public SelectJoinBuilder(String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder(String sql, String tableName) {
|
||||
this.tableName = tableName;
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public void setSql(String sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder field(String field) {
|
||||
this.fieldList.add(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder field(List<String> field) {
|
||||
this.fieldList.addAll(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder join(JoinCondition joinCondition) {
|
||||
this.joinConditions.add(joinCondition);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder join(List<JoinCondition> joinConditions) {
|
||||
this.joinConditions.addAll(joinConditions);
|
||||
return this;
|
||||
}
|
||||
public SelectJoinBuilder rightJoin(JoinCondition joinCondition) {
|
||||
this.rightConditions.add(joinCondition);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder rightJoin(List<JoinCondition> joinConditions) {
|
||||
this.rightConditions.addAll(joinConditions);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder leftJoin(JoinCondition joinCondition) {
|
||||
this.leftConditions.add(joinCondition);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectJoinBuilder leftJoin(List<JoinCondition> joinConditions) {
|
||||
this.leftConditions.addAll(joinConditions);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectCondition build() {
|
||||
StringBuilder stringBuilder = new StringBuilder(" ");
|
||||
if (StringUtils.isEmpty(this.sql)) {
|
||||
this.sql = SELECT + " ";
|
||||
this.sql += getFieldStr(this.fieldList);
|
||||
stringBuilder.append(" FROM ");
|
||||
stringBuilder.append(this.tableName).append(" ");
|
||||
}
|
||||
for (JoinCondition condition : this.joinConditions) {
|
||||
stringBuilder
|
||||
.append(" JOIN ")
|
||||
.append(condition.getName())
|
||||
.append(" ON ")
|
||||
.append(condition.getName())
|
||||
.append(".")
|
||||
.append(condition.getField())
|
||||
.append(" = ")
|
||||
.append(condition.getFkTable())
|
||||
.append(".")
|
||||
.append(condition.getJoinField())
|
||||
.append(" ");
|
||||
}
|
||||
|
||||
for (JoinCondition condition : this.leftConditions) {
|
||||
stringBuilder
|
||||
.append(" LEFT JOIN ")
|
||||
.append(condition.getName())
|
||||
.append(" ON ")
|
||||
.append(condition.getName())
|
||||
.append(".")
|
||||
.append(condition.getField())
|
||||
.append(" = ")
|
||||
.append(condition.getFkTable())
|
||||
.append(".")
|
||||
.append(condition.getJoinField())
|
||||
.append(" ");
|
||||
}
|
||||
|
||||
for (JoinCondition condition : this.rightConditions) {
|
||||
stringBuilder
|
||||
.append(" RIGHT JOIN ")
|
||||
.append(condition.getName())
|
||||
.append(" ON ")
|
||||
.append(condition.getName())
|
||||
.append(".")
|
||||
.append(condition.getField())
|
||||
.append(" = ")
|
||||
.append(condition.getFkTable())
|
||||
.append(".")
|
||||
.append(condition.getJoinField())
|
||||
.append(" ");
|
||||
}
|
||||
this.sql += stringBuilder.toString();
|
||||
return new SelectCondition(this.sql);
|
||||
}
|
||||
}
|
||||
|
||||
public static class SelectSqlJoinBuilder {
|
||||
private String sql = "";
|
||||
|
||||
private String joinSql = "";
|
||||
|
||||
private String tableName;
|
||||
|
||||
private String tempTable;
|
||||
|
||||
private List<String> fieldList = new LinkedList<>();
|
||||
|
||||
public SelectSqlJoinBuilder(String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder(String sql, String tableName) {
|
||||
this.sql = sql;
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public String getSql() {
|
||||
return sql;
|
||||
}
|
||||
|
||||
public void setSql(String sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder field(String field) {
|
||||
this.fieldList.add(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder field(List<String> field) {
|
||||
this.fieldList.addAll(field);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder join(String tableName) {
|
||||
this.tempTable = tableName;
|
||||
this.joinSql += " JOIN " + tableName + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder leftJoin(String tableName) {
|
||||
this.tempTable = tableName;
|
||||
this.joinSql += " LEFT JOIN " + tableName + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder rightJoin(String tableName) {
|
||||
this.tempTable = tableName;
|
||||
this.joinSql += " RIGHT JOIN " + tableName + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectSqlJoinBuilder on(String field, String joinTable, String joinField) {
|
||||
this.joinSql += " ON " + this.tempTable + "." + field + "=" + joinTable + "." + joinField + " ";
|
||||
return this;
|
||||
}
|
||||
|
||||
public SelectCondition build() {
|
||||
if (StringUtils.isEmpty(this.sql)) {
|
||||
this.sql = SELECT + " ";
|
||||
this.sql += getFieldStr(this.fieldList);
|
||||
StringBuilder stringBuilder = new StringBuilder(" FROM ");
|
||||
stringBuilder.append(this.tableName).append(" ");
|
||||
this.sql += stringBuilder.toString();
|
||||
}
|
||||
this.sql += this.joinSql;
|
||||
return new SelectCondition(this.sql, this.tableName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.hcframe.base.module.data.module;
|
||||
|
||||
import com.hcframe.base.module.data.constants.QueryConstants;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-12-23
|
||||
* @decription 前端Condition
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
public class WebCondition {
|
||||
// key
|
||||
private String key;
|
||||
// value
|
||||
private Object value;
|
||||
// 符号
|
||||
private int sign;
|
||||
// 第二个value,只有在sign为between的时候生效
|
||||
private Object sValue;
|
||||
// 逗号隔开的value
|
||||
private String values;
|
||||
|
||||
private Integer logic;
|
||||
|
||||
private Integer curves;
|
||||
|
||||
private List<String> valueList;
|
||||
|
||||
public List<String> getValueList() {
|
||||
if (valueList == null) {
|
||||
String[] arr = this.values.split(",");
|
||||
this.valueList = Arrays.asList(arr);
|
||||
}
|
||||
return valueList;
|
||||
}
|
||||
|
||||
public static Condition.ConditionBuilder setSign(WebCondition webCondition,Condition.ConditionBuilder builder) {
|
||||
switch (webCondition.getSign()) {
|
||||
case QueryConstants.LIKE:{
|
||||
return builder.like(webCondition.key, webCondition.value);
|
||||
}
|
||||
case QueryConstants.EQUAL:{
|
||||
return builder.equal(webCondition.key,webCondition.value);
|
||||
}
|
||||
case QueryConstants.BETWEEN:{
|
||||
return builder.between(webCondition.key, webCondition.value,webCondition.sValue);
|
||||
}
|
||||
case QueryConstants.GT:{
|
||||
return builder.gt(webCondition.key, webCondition.value);
|
||||
}
|
||||
case QueryConstants.GTE:{
|
||||
return builder.gte(webCondition.key, webCondition.value);
|
||||
}
|
||||
case QueryConstants.LT:{
|
||||
return builder.lt(webCondition.key, webCondition.value);
|
||||
}
|
||||
case QueryConstants.LTE:{
|
||||
return builder.lte(webCondition.key, webCondition.value);
|
||||
}
|
||||
case QueryConstants.IN:{
|
||||
String[] strings = webCondition.value.toString().split(",");
|
||||
return builder.in(webCondition.key, Arrays.asList(strings));
|
||||
}
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected sign value: " + webCondition.getLogic());
|
||||
}
|
||||
}
|
||||
|
||||
public static Condition.ConditionBuilder setLogic(WebCondition webCondition,Condition.ConditionBuilder builder) {
|
||||
switch (webCondition.getLogic()) {
|
||||
case QueryConstants.AND:{
|
||||
return builder.and();
|
||||
}
|
||||
case QueryConstants.OR:{
|
||||
return builder.or();
|
||||
}
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected Logic value: " + webCondition.getLogic());
|
||||
}
|
||||
}
|
||||
|
||||
public static Condition.ConditionBuilder setCurves(WebCondition webCondition,Condition.ConditionBuilder builder) {
|
||||
switch (webCondition.getCurves()) {
|
||||
case QueryConstants.L_CURVES:{
|
||||
return builder.leftCurves();
|
||||
}
|
||||
case QueryConstants.R_CURVES:{
|
||||
return builder.rightCurves();
|
||||
}
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected Curves value: " + webCondition.getLogic());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.hcframe.base.module.data.service;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface TableService {
|
||||
|
||||
int save(OsSysTable osSysTable, Map<String, Object> map);
|
||||
|
||||
ResultVO<Map<String,Object>> saveWithDate(OsSysTable osSysTable, Map<String, Object> map);
|
||||
|
||||
ResultVO<Integer> update(OsSysTable osSysTable, Map<String, Object> map, Integer version);
|
||||
|
||||
ResultVO<Integer> updateWithDate(OsSysTable tableName, Map<String, Object> map, Integer version);
|
||||
|
||||
ResultVO<Integer> delete(OsSysTable tableName, String ids);
|
||||
|
||||
ResultVO<List<Map<String,Object>>> getListNoPage(OsSysTable tableName, Map<String, Object> map);
|
||||
|
||||
ResultVO<Integer> updateBatch(OsSysTable osSysTable, Map<String, Object> map);
|
||||
|
||||
ResultVO<Integer> updateBatchWithDate(OsSysTable osSysTable, Map<String, Object> map);
|
||||
|
||||
ResultVO<Integer> saveBatch(OsSysTable osSysTable, String map);
|
||||
|
||||
ResultVO<Integer> saveBatchWithDate(OsSysTable osSysTable, String data);
|
||||
|
||||
ResultVO<Map<String,Object>> getBaseTableInfo(String tableNames);
|
||||
|
||||
PageInfo<Map<String,Object>> searchSingleTables(String map, OsSysTable tableName, WebPageInfo webPageInfo);
|
||||
|
||||
|
||||
PageInfo<Map<String,Object>> searchJoinTables(String data, WebPageInfo webPageInfo, OsSysTable tableName);
|
||||
|
||||
ResultVO<Integer> logicDelete(OsSysTable tableName, String ids);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package com.hcframe.base.module.data.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.common.utils.TableNameUtil;
|
||||
import com.hcframe.base.module.data.constants.FieldConstants;
|
||||
import com.hcframe.base.module.data.constants.QueryConstants;
|
||||
import com.hcframe.base.module.data.dao.TableMapper;
|
||||
import com.hcframe.base.module.data.module.*;
|
||||
import com.hcframe.base.module.data.service.TableService;
|
||||
import com.hcframe.base.module.data.exception.SqlException;
|
||||
import com.hcframe.base.module.tableconfig.entity.OsSysTable;
|
||||
import com.hcframe.base.module.cache.impl.TableCache;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.*;
|
||||
|
||||
/***
|
||||
* @author lhc
|
||||
* @description 事务层,主要编写业务逻辑,尽量所有的业务都在事务层编写
|
||||
*/
|
||||
@Service
|
||||
public class TableServiceImpl implements TableService {
|
||||
|
||||
final
|
||||
TableMapper tableMapper;
|
||||
|
||||
final
|
||||
TableNameUtil tableNameUtil;
|
||||
|
||||
final
|
||||
BaseMapper baseMapper;
|
||||
|
||||
final
|
||||
TableCache tableCache;
|
||||
|
||||
public TableServiceImpl(TableMapper tableMapper, TableNameUtil tableNameUtil, @Qualifier(BaseMapperImpl.BASE) BaseMapper baseMapper, TableCache tableCache) {
|
||||
this.tableMapper = tableMapper;
|
||||
this.tableNameUtil = tableNameUtil;
|
||||
this.baseMapper = baseMapper;
|
||||
this.tableCache = tableCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int save(OsSysTable osSysTable, Map<String, Object> map) {
|
||||
return baseMapper.save(DataMap.builder().sysOsTable(osSysTable).data(map).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Map<String, Object>> saveWithDate(OsSysTable osSysTable, Map<String, Object> map) {
|
||||
map.put(FieldConstants.CREATE_TIME.toString(), new Date());
|
||||
map.put(FieldConstants.UPDATE_TIME.toString(), new Date());
|
||||
int i = baseMapper.save(DataMap.builder().sysOsTable(osSysTable).data(map).build());
|
||||
SqlException.operation(i, "新增数据失败");
|
||||
return ResultVO.getSuccess(map);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> update(OsSysTable osSysTable, Map<String, Object> map, Integer version) {
|
||||
Object pk = map.get(osSysTable.getTablePk());
|
||||
map.remove(osSysTable.getTablePk());
|
||||
return versionValid(osSysTable, map, version, pk);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> updateWithDate(OsSysTable osSysTable, Map<String, Object> map, Integer version) {
|
||||
Object pk = map.get(osSysTable.getTablePk());
|
||||
map.put(FieldConstants.UPDATE_TIME.toString(), new Date());
|
||||
map.remove(osSysTable.getTablePk());
|
||||
map.remove(FieldConstants.CREATE_TIME.toString());
|
||||
return versionValid(osSysTable, map, version, pk);
|
||||
}
|
||||
|
||||
private ResultVO<Integer> versionValid(OsSysTable osSysTable, Map<String, Object> map, Integer version, Object pk) {
|
||||
if (!StringUtils.isEmpty(version)) {
|
||||
DataMap dataMap = DataMap.builder().sysOsTable(osSysTable).pkValue(pk).data(map).build();
|
||||
Map<String, Object> data = baseMapper.selectByPk(dataMap);
|
||||
Integer newVersion = Integer.parseInt(data.get(FieldConstants.VERSION.toString()).toString());
|
||||
if (!version.equals(newVersion)) {
|
||||
throw new ServiceException("更新失败");
|
||||
} else {
|
||||
map.put(DataMap.VERSION, version + 1);
|
||||
}
|
||||
}
|
||||
return updateByPk(osSysTable, map, pk);
|
||||
}
|
||||
|
||||
private ResultVO<Integer> updateByPk(OsSysTable osSysTable, Map<String, Object> map, Object pk) {
|
||||
map.remove("ROW_ID");
|
||||
// 设置更新项
|
||||
DataMap dataMap = DataMap.builder()
|
||||
.sysOsTable(osSysTable)
|
||||
.pkValue(pk)
|
||||
.data(map)
|
||||
.build();
|
||||
int i = baseMapper.updateByPk(dataMap);
|
||||
SqlException.operation(i, "更新失败");
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> delete(OsSysTable osSysTable, String ids) {
|
||||
int i = baseMapper.deleteInPk(DataMap.builder().sysOsTable(osSysTable).ids(ids).build());
|
||||
SqlException.operation(i, "删除失败");
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ResultVO<List<Map<String, Object>>> getListNoPage(OsSysTable tableName, Map<String, Object> map) {
|
||||
List<Map<String, Object>> list = baseMapper.selectByEqual(DataMap.builder().sysOsTable(tableName).build(), map);
|
||||
return ResultVO.getSuccess(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> updateBatch(OsSysTable osSysTable, Map<String, Object> map) {
|
||||
String ids = (String) map.get(osSysTable.getTablePk());
|
||||
map.remove(osSysTable.getTablePk());
|
||||
int i = baseMapper.updateInPk(DataMap.builder().sysOsTable(osSysTable).ids(ids).build());
|
||||
SqlException.operation(i, "更新失败");
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> updateBatchWithDate(OsSysTable osSysTable, Map<String, Object> map) {
|
||||
String ids = (String) map.get(osSysTable.getTablePk());
|
||||
map.put(FieldConstants.UPDATE_TIME.toString(), new Date());
|
||||
map.remove(osSysTable.getTablePk());
|
||||
map.remove(FieldConstants.CREATE_TIME.toString());
|
||||
int i = baseMapper.updateInPk(DataMap.builder().sysOsTable(osSysTable).ids(ids).data(map).build());
|
||||
SqlException.operation(i, "更新失败");
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultVO<Integer> saveBatch(OsSysTable osSysTable, String map) {
|
||||
JSONArray jsonArray = JSONArray.parseArray(map);
|
||||
int i = 0;
|
||||
for (Object object : jsonArray) {
|
||||
Map<String, Object> data = JSON.parseObject(object.toString());
|
||||
i = baseMapper.save(DataMap.builder().sysOsTable(osSysTable).data(data).build());
|
||||
SqlException.operation(i, "批量新增失败");
|
||||
}
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> saveBatchWithDate(OsSysTable osSysTable, String data) {
|
||||
JSONArray jsonArray = JSONArray.parseArray(data);
|
||||
int i = 0;
|
||||
for (Object object : jsonArray) {
|
||||
Map<String, Object> map = JSON.parseObject(object.toString());
|
||||
map.put(FieldConstants.CREATE_TIME.toString(), new Date());
|
||||
map.put(FieldConstants.UPDATE_TIME.toString(), new Date());
|
||||
i = baseMapper.save(DataMap.builder().sysOsTable(osSysTable).data(map).build());
|
||||
SqlException.operation(i, "批量新增失败");
|
||||
}
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Map<String, Object>> getBaseTableInfo(String tableNames) {
|
||||
return ResultVO.getSuccess(tableNameUtil.getBaseTableInfo(tableNames));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> searchSingleTables(String map, OsSysTable tableName, WebPageInfo webPageInfo) {
|
||||
DataMap dataMap = DataMap.builder().sysOsTable(tableName).build();
|
||||
Condition.ConditionBuilder builder = Condition.creatCriteria(dataMap);
|
||||
if (!StringUtils.isEmpty(map)) {
|
||||
try {
|
||||
map = URLDecoder.decode(map, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
JSONArray jsonArray = JSON.parseArray(map);
|
||||
builder = getQueryBuilder(jsonArray, builder);
|
||||
}
|
||||
return baseMapper.selectByCondition(builder.build(), webPageInfo);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public PageInfo<Map<String, Object>> searchJoinTables(String data, WebPageInfo webPageInfo, OsSysTable tableName) {
|
||||
if (!StringUtils.isEmpty(data)) {
|
||||
try {
|
||||
data = URLDecoder.decode(data, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new ServiceException(e);
|
||||
}
|
||||
JSONObject jsonObject = JSON.parseObject(data);
|
||||
JSONArray query = JSON.parseArray(jsonObject.getString(QueryConstants.QUERY));
|
||||
JSONArray join = JSON.parseArray(jsonObject.getString(QueryConstants.JOIN));
|
||||
SelectCondition.SelectJoinBuilder selectJoinBuilder = SelectCondition.joinBuilder(tableName.getTableName());
|
||||
for (Object o : join) {
|
||||
JoinCondition joinCondition = JSON.parseObject(String.valueOf(o), JoinCondition.class);
|
||||
joinCondition.setName(tableNameUtil.getTableName(joinCondition.getName()).getTableName());
|
||||
joinCondition.setFkTable(tableNameUtil.getTableName(joinCondition.getFkTable()).getTableName());
|
||||
selectJoinBuilder = selectJoinBuilder.join(joinCondition);
|
||||
}
|
||||
SelectCondition selectCondition = selectJoinBuilder.build();
|
||||
Condition.ConditionBuilder builder = Condition.creatCriteria(selectCondition);
|
||||
builder = getQueryBuilder(query, builder);
|
||||
return baseMapper.selectByCondition(builder.build(), webPageInfo);
|
||||
} else {
|
||||
throw new ServiceException("参数错误");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO<Integer> logicDelete(OsSysTable tableName, String ids) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put(FieldConstants.DELETED.toString(), 1);
|
||||
DataMap dataMap = DataMap.builder().sysOsTable(tableName).ids(ids).data(map).build();
|
||||
Condition condition = Condition.creatCriteria().andIn(dataMap.getPkName(), dataMap.getIdList()).build();
|
||||
int i = baseMapper.updateByCondition(dataMap, condition);
|
||||
SqlException.operation(i, "删除失败");
|
||||
return ResultVO.getSuccess(i);
|
||||
}
|
||||
|
||||
private Condition.ConditionBuilder getQueryBuilder(JSONArray query, Condition.ConditionBuilder builder) {
|
||||
for (Object qObj : query) {
|
||||
WebCondition webCondition = JSON.parseObject(String.valueOf(qObj), WebCondition.class);
|
||||
if (!StringUtils.isEmpty(webCondition.getLogic())) {
|
||||
builder = WebCondition.setLogic(webCondition, builder);
|
||||
} else {
|
||||
builder = builder.and();
|
||||
}
|
||||
if (!StringUtils.isEmpty(webCondition.getCurves())) {
|
||||
builder = WebCondition.setCurves(webCondition, builder);
|
||||
}
|
||||
builder = WebCondition.setSign(webCondition, builder);
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(SelectCondition.builder().tableName("table").build().getSql());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.hcframe.base.module.datasource.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @description 规定数据源类型注解
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
// 方法注解
|
||||
@Target(ElementType.METHOD)
|
||||
// 运行时可见
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface DatasourceAnno {
|
||||
// 填写数据源类型key
|
||||
String value();
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.hcframe.base.module.datasource.aop;
|
||||
|
||||
import com.hcframe.base.common.utils.RedisUtil;
|
||||
import com.hcframe.base.module.datasource.annotation.DatasourceAnno;
|
||||
import com.hcframe.base.module.datasource.dynamic.DBContextHolder;
|
||||
import com.hcframe.base.module.shiro.dao.FtTokenDao;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020.09.23
|
||||
* @description 通过Aop形式,设置数据源,默认数据源设置为master节点
|
||||
*/
|
||||
@Order(5)
|
||||
@Aspect
|
||||
@Component
|
||||
public class DataSourceAnnoOperation {
|
||||
|
||||
@Autowired
|
||||
FtTokenDao osTokenMapper;
|
||||
|
||||
@Autowired
|
||||
RedisUtil redisUtil;
|
||||
|
||||
@Around("@annotation(com.hcframe.base.module.datasource.annotation.DatasourceAnno)")
|
||||
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
|
||||
// 获取方法签名
|
||||
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
|
||||
// 获取方法
|
||||
Method method = methodSignature.getMethod();
|
||||
// 获取方法上面的注解
|
||||
DatasourceAnno dataSourceAnno = method.getAnnotation(DatasourceAnno.class);
|
||||
String key = dataSourceAnno.value();
|
||||
DBContextHolder.clearDataSource();
|
||||
DBContextHolder.setDataSource(key);
|
||||
return pjp.proceed();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.hcframe.base.module.datasource.aop;
|
||||
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceConfigDao;
|
||||
import com.hcframe.base.module.datasource.dynamic.DBContextHolder;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.After;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.annotation.Before;
|
||||
import org.aspectj.lang.annotation.Pointcut;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
* @description 通过注解形式设置数据源,优先级为最高。接口添加注解后,以注解数据源为准。
|
||||
*/
|
||||
@Aspect
|
||||
@Order(1)
|
||||
@Component
|
||||
public class DataSourceAop {
|
||||
|
||||
@Autowired
|
||||
DatasourceConfigDao datasourceConfigDao;
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(DataSourceAop.class);
|
||||
|
||||
//这个切点的表达式需要根据自己的项目来写
|
||||
@Pointcut("execution(public * com..*.controller..*(..))")
|
||||
public void log() {
|
||||
|
||||
}
|
||||
|
||||
@Before("log()")
|
||||
public void doBefore(JoinPoint joinPoint) {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
String key = request.getParameter("datasourceKey");
|
||||
if (StringUtils.isBlank(key)) {
|
||||
DBContextHolder.setDataSource(DataUnit.MASTER);
|
||||
} else {
|
||||
DBContextHolder.setDataSource(key);
|
||||
}
|
||||
}
|
||||
|
||||
@After("log()")
|
||||
public void doAfter() {
|
||||
DBContextHolder.clearDataSource();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.hcframe.base.module.datasource.config;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import com.hcframe.base.common.Mapper;
|
||||
import com.hcframe.base.module.datasource.dynamic.MyDynamicDataSource;
|
||||
import org.mybatis.spring.SqlSessionFactoryBean;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
|
||||
import org.slf4j.Logger;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
* @description 配置项目数据源配置类
|
||||
*/
|
||||
@Configuration
|
||||
// 配置tk.mybatis参数及通用mapper,指定sqlSession工厂Bean
|
||||
@tk.mybatis.spring.annotation.MapperScan(basePackages = "com.hcframe.**.dao", //这里扫描dao层的接口
|
||||
sqlSessionFactoryRef = "sqlSessionFactoryBean222",
|
||||
markerInterface = Mapper.class //指定tkmybatis 中的通用mapper
|
||||
)
|
||||
// 配置mybatis参数,指定sqlSession工厂Bean
|
||||
@MapperScan(basePackages = "com.hcframe.**.dao",sqlSessionFactoryRef = "sqlSessionFactoryBean222")
|
||||
@EnableConfigurationProperties(MybatisProperties.class)
|
||||
public class DataSourceConfiguration {
|
||||
|
||||
private final MybatisProperties properties;
|
||||
|
||||
private final Logger logger = org.slf4j.LoggerFactory.getLogger(DataSourceConfiguration.class);
|
||||
|
||||
public DataSourceConfiguration(MybatisProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
* @Bean 防止数据监控报错,无法查看数据源
|
||||
* @ConfigurationProperties 会把配置文件的参数自动赋值到dataSource里。
|
||||
* @Primary 用于标识默认使用的 DataSource Bean
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "spring.datasource.druid")
|
||||
@Primary
|
||||
@Bean(name = "masterDataSource")
|
||||
public DataSource masterDataSource() {
|
||||
return new DruidDataSource();
|
||||
}
|
||||
|
||||
@Bean(name = "dynamicDataSource")
|
||||
public DataSource dynamicDataSource() {
|
||||
MyDynamicDataSource myDynamicDataSource = new MyDynamicDataSource();
|
||||
// 配置多数据源
|
||||
Map<Object, Object> targetDataSources = new HashMap<>(1);
|
||||
targetDataSources.put("master", masterDataSource());
|
||||
myDynamicDataSource.setTargetDataSources(targetDataSources);
|
||||
return myDynamicDataSource;
|
||||
}
|
||||
/**
|
||||
* 配置 SqlSessionFactoryBean
|
||||
*/
|
||||
@Bean(value = "sqlSessionFactoryBean222")
|
||||
public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
|
||||
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
|
||||
sqlSessionFactoryBean.setTypeAliasesPackage("com.common.**.entity");
|
||||
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
|
||||
sqlSessionFactoryBean.setMapperLocations(this.properties.resolveMapperLocations());
|
||||
}
|
||||
sqlSessionFactoryBean.setDataSource(dynamicDataSource());
|
||||
return sqlSessionFactoryBean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 注入 DataSourceTransactionManager 用于事务管理
|
||||
*/
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager() {
|
||||
return new DataSourceTransactionManager(dynamicDataSource());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.hcframe.base.module.datasource.controller;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.module.datasource.annotation.DatasourceAnno;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
import com.hcframe.base.module.datasource.service.DataSourceService;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiImplicitParam;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
@Api(tags = "数据源信息管理接口")
|
||||
@RestController
|
||||
@RequestMapping("/datasource")
|
||||
public class DataSourceController {
|
||||
|
||||
|
||||
@Autowired
|
||||
DataSourceService dataSourceService;
|
||||
|
||||
@GetMapping("hasSource")
|
||||
@ApiOperation(value = "判断是否配置数据源")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO isFirst() {
|
||||
return dataSourceService.hasSource();
|
||||
}
|
||||
|
||||
@GetMapping("list")
|
||||
@ApiOperation(value = "获取数据源信息列表")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO getDataSourceList(WebPageInfo webPageInfo, DatasourceConfig datasourceConfig) {
|
||||
return ResultVO.getSuccess(dataSourceService.list(webPageInfo, datasourceConfig));
|
||||
}
|
||||
|
||||
@PostMapping("test")
|
||||
@ApiOperation(value = "测试数据库是否正常连接")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO getTest(DatasourceConfig datasourceConfig) {
|
||||
return dataSourceService.test(datasourceConfig);
|
||||
}
|
||||
|
||||
@PostMapping("")
|
||||
@ApiOperation(value = "新增数据库信息")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO saveDatasource(DatasourceConfig datasourceConfig) {
|
||||
return dataSourceService.save(datasourceConfig);
|
||||
}
|
||||
|
||||
@PutMapping("")
|
||||
@ApiOperation(value = "更新数据库信息")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO update(DatasourceConfig datasourceConfig) {
|
||||
return dataSourceService.update(datasourceConfig);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@ApiOperation(value = "删除数据库信息")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO delete(@PathVariable Integer id) {
|
||||
return dataSourceService.delete(id);
|
||||
}
|
||||
|
||||
@GetMapping("unique")
|
||||
@ApiOperation(value = "数据库Key或数据库名称是否唯一")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO getUnique(String key, String name) {
|
||||
return dataSourceService.getUnique(key, name);
|
||||
}
|
||||
|
||||
@PutMapping("enabled/{id}")
|
||||
@ApiOperation(value = "启用/禁用")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
@ApiImplicitParam(name = "status", value = "启用为1,禁用为0", required = true)
|
||||
public ResultVO enableDatasource(@PathVariable Integer id, @RequestParam Integer status) {
|
||||
return dataSourceService.enableDatasource(id, status);
|
||||
}
|
||||
|
||||
@PutMapping("default/{id}")
|
||||
@ApiOperation(value = "设置默认数据库")
|
||||
@DatasourceAnno(value = DataUnit.SQLITE)
|
||||
public ResultVO setDefault(@PathVariable Integer id) {
|
||||
return dataSourceService.setDefault(id);
|
||||
}
|
||||
|
||||
@GetMapping("all")
|
||||
@ApiOperation(value = "获取全部列表(启用)")
|
||||
@DatasourceAnno(value = DataUnit.SQLITE)
|
||||
public ResultVO getAllList() {
|
||||
return dataSourceService.getAllList();
|
||||
}
|
||||
|
||||
@PostMapping("token")
|
||||
@ApiOperation(value = "token校验")
|
||||
@DatasourceAnno(value = DataUnit.SQLITE)
|
||||
public ResultVO validateToken(String token) {
|
||||
return dataSourceService.validateToken(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.hcframe.base.module.datasource.controller;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.module.datasource.annotation.DatasourceAnno;
|
||||
import com.hcframe.base.module.datasource.service.DatasourceConfigService;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
@Api(tags = "数据源配置管理接口")
|
||||
@RestController
|
||||
@RequestMapping("dataconfig")
|
||||
public class DatasourceConfigController {
|
||||
|
||||
@Autowired
|
||||
DatasourceConfigService datasourceConfigService;
|
||||
|
||||
@PostMapping(value = "add")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
@ApiOperation(value = "新增")
|
||||
public ResultVO add(Integer id) {
|
||||
return datasourceConfigService.add(id);
|
||||
}
|
||||
|
||||
@GetMapping("")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
@ApiOperation(value = "列表显示数据源状态")
|
||||
public ResultVO getRuntimeList() {
|
||||
return datasourceConfigService.getRuntimeList();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{key}")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
@ApiOperation(value = "终止数据源使用")
|
||||
public ResultVO deleteRuntimeSource(@PathVariable String key) {
|
||||
return datasourceConfigService.deleteRuntimeSource(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.hcframe.base.module.datasource.controller;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.module.datasource.annotation.DatasourceAnno;
|
||||
import com.hcframe.base.module.datasource.service.DatasourceTypeService;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-28
|
||||
* @description 数据库类型配置表
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("datatype")
|
||||
public class DatasourceTypeController {
|
||||
|
||||
@Autowired
|
||||
DatasourceTypeService datasourceTypeService;
|
||||
|
||||
@GetMapping("all")
|
||||
@ApiOperation(value = "获取全部数据库类型信息")
|
||||
@DatasourceAnno(DataUnit.SQLITE)
|
||||
public ResultVO getAllInfo() {
|
||||
return ResultVO.getSuccess(datasourceTypeService.getAllInfo());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.hcframe.base.module.datasource.dao;
|
||||
|
||||
import com.hcframe.base.common.Mapper;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
|
||||
/**
|
||||
* (DatasourceConfig)表数据库访问层
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-09-23 09:28:03
|
||||
*/
|
||||
public interface DatasourceConfigDao extends Mapper<DatasourceConfig> {
|
||||
|
||||
|
||||
int getCount();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.hcframe.base.module.datasource.dao;
|
||||
|
||||
import com.hcframe.base.common.Mapper;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceToken;
|
||||
|
||||
/**
|
||||
* (DatasourceToken)表数据库访问层
|
||||
*
|
||||
* @author makejava
|
||||
* @since 2020-10-10 10:35:49
|
||||
*/
|
||||
public interface DatasourceTokenDao extends Mapper<DatasourceToken> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.hcframe.base.module.datasource.dao;
|
||||
|
||||
import com.hcframe.base.common.Mapper;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceType;
|
||||
|
||||
/**
|
||||
* (DatasourceType)表数据库访问层
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-09-28 15:18:29
|
||||
*/
|
||||
public interface DatasourceTypeDao extends Mapper<DatasourceType> {
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hcframe.base.module.datasource.dynamic;
|
||||
|
||||
|
||||
import com.hcframe.base.module.datasource.utils.DataSourceUtil;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
* @description 通过ThreadLocal储存当前线程数据源的key
|
||||
*/
|
||||
public class DBContextHolder {
|
||||
// 对当前线程的操作-线程安全的
|
||||
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
|
||||
|
||||
// 调用此方法,切换数据源
|
||||
public static void setDataSource(String dataSource) {
|
||||
if (DataSourceUtil.dataSourceMap.containsKey(dataSource)) {
|
||||
contextHolder.set(dataSource);
|
||||
} else {
|
||||
throw new RuntimeException("数据源:" + dataSource + "不存在");
|
||||
}
|
||||
}
|
||||
|
||||
// 获取数据源
|
||||
public static String getDataSource() {
|
||||
return contextHolder.get();
|
||||
}
|
||||
|
||||
// 删除数据源
|
||||
public static void clearDataSource() {
|
||||
contextHolder.remove();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.hcframe.base.module.datasource.dynamic;
|
||||
|
||||
import com.alibaba.druid.util.StringUtils;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
* @description 重写determineCurrentLookupKey方法,通过DBContextHolder获取数据源key值
|
||||
*/
|
||||
public class MyDynamicDataSource extends AbstractRoutingDataSource {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(MyDynamicDataSource.class);
|
||||
|
||||
@Override
|
||||
public Object determineCurrentLookupKey() {
|
||||
//获取当前线程的数据源,如果不存在使用master数据源
|
||||
String datasource = DBContextHolder.getDataSource();
|
||||
if (StringUtils.isEmpty(datasource)) {
|
||||
datasource = DataUnit.MASTER;
|
||||
}
|
||||
logger.info("datasource=" + datasource);
|
||||
return datasource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.hcframe.base.module.datasource.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* (DatasourceConfig)实体类
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-09-23 09:28:03
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
@ApiModel
|
||||
public class DatasourceConfig implements Serializable {
|
||||
private static final long serialVersionUID = 188640098731075764L;
|
||||
|
||||
public static final int ENABLE = 1;
|
||||
public static final int DISABLE = 0;
|
||||
public static final int DEFAULT = 1;
|
||||
public static final int UNDEFAULT = 0;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator="JDBC")
|
||||
private Integer datasourceId;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "驱动包地址",
|
||||
dataType = "String"
|
||||
)
|
||||
private String driverClassName;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库连接url",
|
||||
example = "",
|
||||
dataType = "String"
|
||||
)
|
||||
private String url;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库用户名",
|
||||
dataType = "String"
|
||||
)
|
||||
private String username;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库密码",
|
||||
dataType = "String"
|
||||
)
|
||||
private String password;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库key(数据库别名)",
|
||||
example = "",
|
||||
dataType = "String"
|
||||
)
|
||||
private String commonAlias;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库类型",
|
||||
example = "mysql",
|
||||
dataType = "String"
|
||||
)
|
||||
private String commonType;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "是否启用数据库",
|
||||
example = "1",
|
||||
dataType = "Integer"
|
||||
)
|
||||
private Integer sysEnabled;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "是否是默认数据库",
|
||||
example = "1",
|
||||
dataType = "Integer"
|
||||
)
|
||||
private Integer isDefault;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库库名",
|
||||
dataType = "String"
|
||||
)
|
||||
private String schemaName;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库中文描述",
|
||||
dataType = "String"
|
||||
)
|
||||
private String sysDescription;
|
||||
|
||||
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date createTime;
|
||||
|
||||
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date updateTime;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.hcframe.base.module.datasource.entity;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* (DatasourceToken)实体类
|
||||
*
|
||||
* @author makejava
|
||||
* @since 2020-10-10 10:35:49
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
public class DatasourceToken implements Serializable {
|
||||
private static final long serialVersionUID = 490365047847182899L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator="JDBC")
|
||||
private Integer tokenId;
|
||||
|
||||
private String token;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.hcframe.base.module.datasource.entity;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* (DatasourceType)实体类
|
||||
*
|
||||
* @author lhc
|
||||
* @since 2020-09-28 15:18:29
|
||||
*/
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Data
|
||||
@ApiModel
|
||||
public class DatasourceType implements Serializable {
|
||||
private static final long serialVersionUID = 331087641518717829L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator="JDBC")
|
||||
private Integer typeId;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "Key",
|
||||
dataType = "String"
|
||||
)
|
||||
private String typeKey;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "名称",
|
||||
dataType = "String"
|
||||
)
|
||||
private String typeValue;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "驱动类地址",
|
||||
dataType = "String"
|
||||
)
|
||||
private String driver;
|
||||
|
||||
@ApiModelProperty(
|
||||
value = "数据库校验语句",
|
||||
dataType = "String"
|
||||
)
|
||||
private String validateQuery;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hcframe.base.module.datasource.service;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
public interface DataSourceService {
|
||||
PageInfo<DatasourceConfig> list(WebPageInfo webPageInfo, DatasourceConfig datasourceConfig);
|
||||
|
||||
ResultVO save(DatasourceConfig datasourceConfig);
|
||||
|
||||
ResultVO update(DatasourceConfig datasourceConfig);
|
||||
|
||||
ResultVO delete(Integer id);
|
||||
|
||||
ResultVO hasSource();
|
||||
|
||||
ResultVO getUnique(String key, String name);
|
||||
|
||||
ResultVO test(DatasourceConfig type);
|
||||
|
||||
ResultVO enableDatasource(Integer id, Integer status);
|
||||
|
||||
ResultVO setDefault(Integer id);
|
||||
|
||||
ResultVO getAllList();
|
||||
|
||||
ResultVO validateToken(String token);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.hcframe.base.module.datasource.service;
|
||||
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
public interface DatasourceConfigService {
|
||||
ResultVO add(Integer datasourceConfig);
|
||||
|
||||
ResultVO getRuntimeList();
|
||||
|
||||
ResultVO deleteRuntimeSource(String key);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.hcframe.base.module.datasource.service;
|
||||
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface DatasourceTypeService {
|
||||
List<DatasourceType> getAllInfo();
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package com.hcframe.base.module.datasource.service.impl;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.WebPageInfo;
|
||||
import com.hcframe.base.common.utils.MyPageHelper;
|
||||
import com.hcframe.base.module.data.dao.TableMapper;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceConfigDao;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceTokenDao;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceTypeDao;
|
||||
import com.hcframe.base.module.datasource.dynamic.DBContextHolder;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceToken;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceType;
|
||||
import com.hcframe.base.module.datasource.service.DataSourceService;
|
||||
import com.hcframe.base.module.datasource.utils.DataSourceUtil;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tk.mybatis.mapper.entity.Example;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
@Service
|
||||
public class DataSourceServiceImpl implements DataSourceService {
|
||||
|
||||
@Autowired
|
||||
DatasourceConfigDao datasourceConfigDao;
|
||||
|
||||
@Autowired
|
||||
DatasourceTypeDao datasourceTypeDao;
|
||||
|
||||
@Autowired
|
||||
DatasourceTokenDao datasourceTokenDao;
|
||||
|
||||
@Autowired
|
||||
TableMapper tableMapper;
|
||||
|
||||
@Override
|
||||
public PageInfo<DatasourceConfig> list(WebPageInfo webPageInfo, DatasourceConfig datasourceConfig) {
|
||||
MyPageHelper.start(webPageInfo);
|
||||
Example example = new Example(DatasourceConfig.class);
|
||||
Example.Criteria criteria = example.createCriteria();
|
||||
if (StringUtils.isNotBlank(datasourceConfig.getCommonAlias())) {
|
||||
criteria = criteria.andLike("commonAlias", "%" + datasourceConfig.getCommonAlias() + "%");
|
||||
}
|
||||
if (StringUtils.isNotBlank(datasourceConfig.getCommonType())) {
|
||||
criteria = criteria.andEqualTo("commonType", datasourceConfig.getCommonType());
|
||||
}
|
||||
if (StringUtils.isNotBlank(datasourceConfig.getSysDescription())) {
|
||||
criteria.andEqualTo("sysDescription", datasourceConfig.getSysDescription());
|
||||
}
|
||||
List<DatasourceConfig> list = datasourceConfigDao.selectByExample(example);
|
||||
for (DatasourceConfig datasourceConfig1 : list) {
|
||||
datasourceConfig1.setPassword(DataUnit.PASSWORD);
|
||||
}
|
||||
return new PageInfo<>(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultVO save(DatasourceConfig datasourceConfig) {
|
||||
datasourceConfig.setUpdateTime(new Date());
|
||||
datasourceConfig.setCreateTime(new Date());
|
||||
boolean flag = false;
|
||||
if (datasourceConfig.getIsDefault() == DatasourceConfig.DEFAULT) {
|
||||
datasourceConfig.setIsDefault(DatasourceConfig.UNDEFAULT);
|
||||
flag = true;
|
||||
}
|
||||
int i = datasourceConfigDao.insertSelective(datasourceConfig);
|
||||
if (flag) {
|
||||
setDefault(datasourceConfig.getDatasourceId());
|
||||
}
|
||||
if (datasourceConfig.getSysEnabled() == DatasourceConfig.ENABLE) {
|
||||
DruidDataSource druidDataSource = DataSourceUtil.initDruid(datasourceConfig.getCommonType());
|
||||
BeanUtils.copyProperties(datasourceConfig, druidDataSource);
|
||||
DataSourceUtil.addMapData(datasourceConfig.getCommonAlias(), druidDataSource, datasourceConfig);
|
||||
if (datasourceConfig.getIsDefault() == DatasourceConfig.DEFAULT) {
|
||||
DataSourceUtil.addMapData(DataUnit.MASTER, druidDataSource, datasourceConfig);
|
||||
}
|
||||
}
|
||||
DataSourceUtil.flushDataSource();
|
||||
if (i < 1) {
|
||||
throw new ServiceException("新增数据源失败");
|
||||
}
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultVO update(DatasourceConfig datasourceConfig) {
|
||||
boolean flag = false;
|
||||
// 是否是master节点
|
||||
boolean masterFlag = false;
|
||||
DatasourceConfig config = datasourceConfigDao.selectByPrimaryKey(datasourceConfig.getDatasourceId());
|
||||
// 判断是否已经启用
|
||||
if (DataSourceUtil.dataSourceMap.containsKey(datasourceConfig.getCommonAlias())) {
|
||||
flag = true;
|
||||
// 启用状态移除数据源
|
||||
DataSourceUtil.removeSource(datasourceConfig.getCommonAlias());
|
||||
// 判断是否是master节点
|
||||
if (config.getIsDefault() == DatasourceConfig.DEFAULT) {
|
||||
// 若是移除数据源
|
||||
DataSourceUtil.removeSource(DataUnit.MASTER);
|
||||
masterFlag = true;
|
||||
}
|
||||
}
|
||||
// 设置更新时间
|
||||
datasourceConfig.setUpdateTime(new Date());
|
||||
if (DataUnit.PASSWORD.equals(datasourceConfig.getPassword())) {
|
||||
datasourceConfig.setPassword(null);
|
||||
}
|
||||
// 更新数据库
|
||||
int i = datasourceConfigDao.updateByPrimaryKeySelective(datasourceConfig);
|
||||
if (flag) {
|
||||
// 将更新后的数据加入
|
||||
DruidDataSource druidDataSource = DataSourceUtil.initDruid(datasourceConfig.getCommonType());
|
||||
BeanUtils.copyProperties(datasourceConfig, druidDataSource);
|
||||
DataSourceUtil.addMapData(datasourceConfig.getCommonAlias(), druidDataSource, datasourceConfig);
|
||||
if (masterFlag) {
|
||||
DataSourceUtil.addMapData(DataUnit.MASTER, druidDataSource, datasourceConfig);
|
||||
}
|
||||
DataSourceUtil.flushDataSource();
|
||||
}
|
||||
if (i < 1) {
|
||||
throw new ServiceException("更新数据源失败");
|
||||
}
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultVO delete(Integer id) {
|
||||
DatasourceConfig datasourceConfig = datasourceConfigDao.selectByPrimaryKey(id);
|
||||
if (datasourceConfig.getIsDefault() == DatasourceConfig.DEFAULT) {
|
||||
throw new ServiceException("不能删除默认数据库!");
|
||||
}
|
||||
if (datasourceConfig.getSysEnabled() == DatasourceConfig.ENABLE) {
|
||||
DataSourceUtil.removeSource(datasourceConfig.getCommonAlias());
|
||||
DataSourceUtil.flushDataSource();
|
||||
}
|
||||
int i = datasourceConfigDao.deleteByPrimaryKey(id);
|
||||
if (i < 1) {
|
||||
throw new ServiceException("删除数据失败");
|
||||
}
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO hasSource() {
|
||||
int i=datasourceConfigDao.getCount();
|
||||
if (i > 0) {
|
||||
return ResultVO.getSuccess();
|
||||
} else {
|
||||
return ResultVO.getFailed("");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO getUnique(String key, String name) {
|
||||
DatasourceConfig datasourceConfig = new DatasourceConfig();
|
||||
boolean flag = true;
|
||||
if (StringUtils.isNotBlank(key)) {
|
||||
datasourceConfig.setCommonAlias(key);
|
||||
}
|
||||
if (StringUtils.isNotBlank(name)) {
|
||||
datasourceConfig.setSysDescription(name);
|
||||
flag = false;
|
||||
}
|
||||
if (DataUnit.SQLITE.equals(key)) {
|
||||
throw new ServiceException("key值不可叫"+DataUnit.SQLITE);
|
||||
}
|
||||
if (DataUnit.MASTER.equals(key)) {
|
||||
throw new ServiceException("key值不可叫" + DataUnit.MASTER);
|
||||
}
|
||||
int i = datasourceConfigDao.selectCount(datasourceConfig);
|
||||
String str = "数据名称重复!";
|
||||
if (flag) {
|
||||
str = "数据库KEY值重复!";
|
||||
}
|
||||
if (i > 0) {
|
||||
throw new ServiceException(str);
|
||||
}
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO test(DatasourceConfig datasourceConfig) {
|
||||
DatasourceConfig datasourceConfig1 = datasourceConfigDao.selectByPrimaryKey(datasourceConfig.getDatasourceId());
|
||||
if (datasourceConfig1 != null&&!DataUnit.PASSWORD.equals(datasourceConfig1.getPassword())) {
|
||||
datasourceConfig = datasourceConfig1;
|
||||
}
|
||||
DatasourceType datasourceType = datasourceTypeDao.selectOne(DatasourceType.builder().typeKey(datasourceConfig.getCommonType()).build());
|
||||
DruidDataSource druidDataSource = new DruidDataSource();
|
||||
BeanUtils.copyProperties(datasourceConfig, druidDataSource);
|
||||
druidDataSource.setBreakAfterAcquireFailure(true);
|
||||
druidDataSource.setConnectionErrorRetryAttempts(0);
|
||||
druidDataSource.setMaxWait(5000);
|
||||
long time = System.currentTimeMillis();
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
String key = uuid + time;
|
||||
DataSourceUtil.addMapData(key, druidDataSource, datasourceConfig);
|
||||
DataSourceUtil.flushDataSource();
|
||||
DBContextHolder.clearDataSource();
|
||||
DBContextHolder.setDataSource(key);
|
||||
try {
|
||||
tableMapper.useSqlByTest(datasourceType.getValidateQuery());
|
||||
} catch (Exception e) {
|
||||
throw new ServiceException("数据库连接失败");
|
||||
}finally {
|
||||
DataSourceUtil.removeSource(key);
|
||||
}
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultVO enableDatasource(Integer id, Integer status) {
|
||||
DatasourceConfig datasourceConfig = datasourceConfigDao.selectOne(DatasourceConfig.builder().datasourceId(id).build());
|
||||
datasourceConfig.setSysEnabled(status);
|
||||
int i = datasourceConfigDao.updateByPrimaryKeySelective(datasourceConfig);
|
||||
if (i < 1) {
|
||||
throw new ServiceException("状态更新失败");
|
||||
}
|
||||
if (status == DatasourceConfig.ENABLE) {
|
||||
DruidDataSource druidDataSource = DataSourceUtil.initDruid(datasourceConfig.getCommonType());
|
||||
DataSourceUtil.addMapData(datasourceConfig.getCommonAlias(), druidDataSource, datasourceConfig);
|
||||
} else {
|
||||
DataSourceUtil.removeSource(datasourceConfig.getCommonAlias());
|
||||
}
|
||||
DataSourceUtil.flushDataSource();
|
||||
DBContextHolder.clearDataSource();
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO setDefault(Integer id) {
|
||||
Example example = new Example(DatasourceConfig.class);
|
||||
example.createCriteria().andEqualTo("isDefault", DatasourceConfig.DEFAULT);
|
||||
int count = datasourceConfigDao.selectCountByExample(example);
|
||||
int i;
|
||||
if (count > 0) {
|
||||
i =datasourceConfigDao.updateByExampleSelective(DatasourceConfig.builder().isDefault(DatasourceConfig.UNDEFAULT).build(), example);
|
||||
if (i < 1) {
|
||||
throw new ServiceException("设置失败");
|
||||
}
|
||||
}
|
||||
i = datasourceConfigDao.updateByPrimaryKeySelective(DatasourceConfig.builder().isDefault(DatasourceConfig.DEFAULT).sysEnabled(DatasourceConfig.ENABLE).datasourceId(id).build());
|
||||
if (i < 1) {
|
||||
throw new ServiceException("设置失败");
|
||||
}
|
||||
DatasourceConfig config = datasourceConfigDao.selectOne(DatasourceConfig.builder().datasourceId(id).build());
|
||||
DruidDataSource druidDataSource = DataSourceUtil.initDruid(config.getCommonType());
|
||||
BeanUtils.copyProperties(config, druidDataSource);
|
||||
DataSourceUtil.addMapData(DataUnit.MASTER, druidDataSource, config);
|
||||
DataSourceUtil.addMapData(config.getCommonAlias(),druidDataSource,config);
|
||||
DataSourceUtil.flushDataSource();
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO getAllList() {
|
||||
return ResultVO.getSuccess(datasourceConfigDao.select(DatasourceConfig.builder().sysEnabled(DatasourceConfig.ENABLE).build()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO validateToken(String token) {
|
||||
int i = datasourceTokenDao.selectCount(DatasourceToken.builder().token(token).build());
|
||||
if (i > 0) {
|
||||
return ResultVO.getSuccess();
|
||||
} else {
|
||||
return ResultVO.getFailed("token不正确");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.hcframe.base.module.datasource.service.impl;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import com.hcframe.base.common.ResultVO;
|
||||
import com.hcframe.base.common.utils.ObjectUtil;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceConfigDao;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceTypeDao;
|
||||
import com.hcframe.base.module.datasource.dynamic.DBContextHolder;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
import com.hcframe.base.module.datasource.service.DataSourceService;
|
||||
import com.hcframe.base.module.datasource.service.DatasourceConfigService;
|
||||
import com.hcframe.base.module.datasource.utils.DataSourceUtil;
|
||||
import com.hcframe.base.module.datasource.utils.DataUnit;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
*/
|
||||
@Service
|
||||
public class DatasourceConfigServiceImpl implements DatasourceConfigService {
|
||||
|
||||
@Autowired
|
||||
DatasourceTypeDao datasourceTypeDao;
|
||||
|
||||
@Autowired
|
||||
DataSourceService dataSourceService;
|
||||
|
||||
@Autowired
|
||||
DatasourceConfigDao datasourceConfigDao;
|
||||
|
||||
@Override
|
||||
public ResultVO add(Integer id) {
|
||||
DatasourceConfig datasourceConfig = datasourceConfigDao.selectByPrimaryKey(id);
|
||||
DruidDataSource druidDataSource = DataSourceUtil.initDruid(datasourceConfig.getCommonType());
|
||||
BeanUtils.copyProperties(datasourceConfig,druidDataSource);
|
||||
//添加数据源到map
|
||||
DataSourceUtil.addMapData(datasourceConfig.getCommonAlias(), druidDataSource,datasourceConfig);
|
||||
//刷新
|
||||
DataSourceUtil.flushDataSource();
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO getRuntimeList() {
|
||||
Map<Object,Object> map = DataSourceUtil.configSourceMap;
|
||||
List<Object> list = new ArrayList<>();
|
||||
String key = "";
|
||||
for (Map.Entry<Object, Object> entry : map.entrySet()) {
|
||||
if (DataUnit.MASTER.equals(entry.getKey())) {
|
||||
DatasourceConfig datasourceConfig = (DatasourceConfig) entry.getValue();
|
||||
key = datasourceConfig.getCommonAlias();
|
||||
} else {
|
||||
list.add(entry.getValue());
|
||||
}
|
||||
}
|
||||
List<Object> resultList = new ArrayList<>();
|
||||
for (Object o : list) {
|
||||
DatasourceConfig datasourceConfig = (DatasourceConfig) o;
|
||||
if (key.equals(datasourceConfig.getCommonAlias())) {
|
||||
datasourceConfig.setIsDefault(DatasourceConfig.DEFAULT);
|
||||
} else {
|
||||
datasourceConfig.setIsDefault(DatasourceConfig.UNDEFAULT);
|
||||
}
|
||||
Map<String, Object> tempMap = ObjectUtil.objToMap(datasourceConfig);
|
||||
DBContextHolder.setDataSource(DataUnit.SQLITE);
|
||||
try {
|
||||
ResultVO resultVO = dataSourceService.test(datasourceConfig);
|
||||
if (resultVO.getCode() == 0) {
|
||||
tempMap.put("status", 1);
|
||||
} else {
|
||||
tempMap.put("status", 0);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
tempMap.put("status", 0);
|
||||
}
|
||||
resultList.add(tempMap);
|
||||
}
|
||||
return ResultVO.getSuccess(resultList);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultVO deleteRuntimeSource(String key) {
|
||||
DataSourceUtil.removeSource(key);
|
||||
DataSourceUtil.flushDataSource();
|
||||
return ResultVO.getSuccess();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.hcframe.base.module.datasource.service.impl;
|
||||
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceTypeDao;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceType;
|
||||
import com.hcframe.base.module.datasource.service.DatasourceTypeService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class DatasourceTypeServiceImpl implements DatasourceTypeService {
|
||||
|
||||
@Autowired
|
||||
DatasourceTypeDao datasourceTypeDao;
|
||||
|
||||
@Override
|
||||
public List<DatasourceType> getAllInfo() {
|
||||
return datasourceTypeDao.selectAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.hcframe.base.module.datasource.utils;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
import com.hcframe.base.common.ServiceException;
|
||||
import com.hcframe.base.common.utils.SpringContextUtil;
|
||||
import com.hcframe.base.common.utils.TokenProccessor;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceConfigDao;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceTokenDao;
|
||||
import com.hcframe.base.module.datasource.dao.DatasourceTypeDao;
|
||||
import com.hcframe.base.module.datasource.dynamic.DBContextHolder;
|
||||
import com.hcframe.base.module.datasource.dynamic.MyDynamicDataSource;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceConfig;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceToken;
|
||||
import com.hcframe.base.module.datasource.entity.DatasourceType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
* @description 数据源工具类,用来缓存管理数据源信息
|
||||
*/
|
||||
@Component
|
||||
public class DataSourceUtil {
|
||||
|
||||
private static DatasourceConfigDao datasourceConfigDao;
|
||||
|
||||
private static DatasourceTypeDao datasourceTypeDao;
|
||||
|
||||
private static DruidDataSource defaultDruid;
|
||||
|
||||
private static DatasourceTokenDao datasourceTokenDao;
|
||||
|
||||
@Autowired
|
||||
DatasourceConfigDao dMapper;
|
||||
|
||||
@Autowired
|
||||
DatasourceTypeDao tMapper;
|
||||
|
||||
@Autowired
|
||||
DatasourceTokenDao tokenDao;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
DataSourceUtil.datasourceConfigDao = dMapper;
|
||||
DataSourceUtil.datasourceTypeDao = tMapper;
|
||||
DataSourceUtil.datasourceTokenDao = tokenDao;
|
||||
}
|
||||
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DataSourceUtil.class);
|
||||
public static final Map<Object, Object> dataSourceMap = new ConcurrentHashMap<>();
|
||||
public static final Map<Object, Object> configSourceMap = new ConcurrentHashMap<>();
|
||||
|
||||
|
||||
/**
|
||||
* 项目启动初始化数据源
|
||||
*/
|
||||
public static void initDataSource() {
|
||||
try {
|
||||
//获取masterDataSource
|
||||
DruidDataSource masterDataSource = (DruidDataSource) SpringContextUtil.getBean(DataUnit.MASTERBEAN);
|
||||
DataSourceUtil.defaultDruid = (DruidDataSource) SpringContextUtil.getBean(DataUnit.MASTERBEAN);
|
||||
addDataSource(DataUnit.MASTER, masterDataSource);
|
||||
addDataSource(DataUnit.SQLITE, masterDataSource);
|
||||
flushDataSource();
|
||||
logger.info("add sqlite success!");
|
||||
} catch (Exception e) {
|
||||
logger.error("add sqlite error!", e);
|
||||
}
|
||||
String token = genToken();
|
||||
try {
|
||||
//初始化其它数据源
|
||||
initOthersDataSource();
|
||||
//刷新数据源
|
||||
flushDataSource();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("add datasource error!");
|
||||
logger.error("请检查Sqlite配置是否正确");
|
||||
}
|
||||
logger.info("数据源Token为:" + token);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新数据源
|
||||
*/
|
||||
public static void flushDataSource() {
|
||||
//获取spring管理的dynamicDataSource
|
||||
MyDynamicDataSource myDynamicDataSource = (MyDynamicDataSource) SpringContextUtil.getBean(DataUnit.DYNAMICBEAN);
|
||||
//将数据源设置到 targetDataSources
|
||||
myDynamicDataSource.setTargetDataSources(dataSourceMap);
|
||||
//将 targetDataSources 中的连接信息放入 resolvedDataSources 管理
|
||||
myDynamicDataSource.afterPropertiesSet();
|
||||
}
|
||||
|
||||
public static void addDataSource(String key, DruidDataSource masterDataSource) {
|
||||
dataSourceMap.put(key, masterDataSource);
|
||||
}
|
||||
|
||||
public static void addMapData(String key, DruidDataSource druidDataSource, DatasourceConfig datasourceConfig) {
|
||||
dataSourceMap.put(key, druidDataSource);
|
||||
datasourceConfig.setPassword(DataUnit.PASSWORD);
|
||||
configSourceMap.put(key, datasourceConfig);
|
||||
}
|
||||
|
||||
public static DatasourceConfig get(String key) {
|
||||
return (DatasourceConfig) configSourceMap.get(key);
|
||||
}
|
||||
|
||||
public static void addConfigSource(String key, DatasourceConfig datasourceConfig) {
|
||||
configSourceMap.put(key, datasourceConfig);
|
||||
}
|
||||
|
||||
public static void removeSource(String key) {
|
||||
dataSourceMap.remove(key);
|
||||
configSourceMap.remove(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化其他数据源
|
||||
*/
|
||||
private static void initOthersDataSource() {
|
||||
// 从Sqlite中获取db列表
|
||||
List<DatasourceConfig> list = datasourceConfigDao.selectAll();
|
||||
if (list != null && list.size() > 0) {
|
||||
// 遍历db列表添加到数据源
|
||||
list.forEach(datasourceConfig -> {
|
||||
if (datasourceConfig.getSysEnabled() == DatasourceConfig.ENABLE) {
|
||||
DruidDataSource druidDataSource = initDruid(datasourceConfig.getCommonType());
|
||||
BeanUtils.copyProperties(datasourceConfig, druidDataSource);
|
||||
addMapData(datasourceConfig.getCommonAlias(), druidDataSource, datasourceConfig);
|
||||
logger.info("add datasource " + datasourceConfig.getSysDescription());
|
||||
if (datasourceConfig.getIsDefault() == DatasourceConfig.DEFAULT) {
|
||||
addMapData(DataUnit.MASTER, druidDataSource, datasourceConfig);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
DBContextHolder.clearDataSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化Druid配置
|
||||
*
|
||||
* @param type
|
||||
*/
|
||||
public static DruidDataSource initDruid(String type) {
|
||||
DruidDataSource druidDataSource = new DruidDataSource();
|
||||
druidDataSource.setInitialSize(defaultDruid.getInitialSize());
|
||||
druidDataSource.setMaxActive(defaultDruid.getMaxActive());
|
||||
druidDataSource.setMaxWait(defaultDruid.getMaxWait());
|
||||
druidDataSource.setTimeBetweenEvictionRunsMillis(defaultDruid.getTimeBetweenEvictionRunsMillis());
|
||||
druidDataSource.setMinEvictableIdleTimeMillis(defaultDruid.getMinEvictableIdleTimeMillis());
|
||||
DatasourceType datasourceType = datasourceTypeDao.selectOne(DatasourceType.builder().typeKey(type).build());
|
||||
druidDataSource.setValidationQuery(datasourceType.getValidateQuery());
|
||||
druidDataSource.setTestWhileIdle(true);
|
||||
druidDataSource.setTestOnBorrow(false);
|
||||
druidDataSource.setBreakAfterAcquireFailure(true);
|
||||
druidDataSource.setConnectionErrorRetryAttempts(0);
|
||||
druidDataSource.setTestOnReturn(false);
|
||||
try {
|
||||
druidDataSource.setFilters("stat,slf4j");
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
druidDataSource.setConnectProperties(defaultDruid.getConnectProperties());
|
||||
if (!type.equals(DataUnit.SQLITE)) {
|
||||
druidDataSource.setPoolPreparedStatements(true);
|
||||
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
|
||||
}
|
||||
return druidDataSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
*/
|
||||
public static String genToken() {
|
||||
String token;
|
||||
List<DatasourceToken> list = datasourceTokenDao.selectAll();
|
||||
if (list == null || list.size() == 0) {
|
||||
TokenProccessor tokenProccessor = TokenProccessor.getInstance();
|
||||
//生成一个token
|
||||
token = tokenProccessor.makeToken();
|
||||
DatasourceToken datasourceToken = DatasourceToken.builder().token(token).build();
|
||||
int i = datasourceTokenDao.insert(datasourceToken);
|
||||
if (i < 1) {
|
||||
throw new ServiceException("新增token失败");
|
||||
} else {
|
||||
return token;
|
||||
}
|
||||
} else {
|
||||
DatasourceToken datasourceToken = list.get(0);
|
||||
token = datasourceToken.getToken();
|
||||
}
|
||||
return token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.hcframe.base.module.datasource.utils;
|
||||
|
||||
/**
|
||||
* @author lhc
|
||||
* @date 2020-09-23
|
||||
* @description 数据源相关静态常量
|
||||
*/
|
||||
public class DataUnit {
|
||||
|
||||
public static final String MASTER = "master";
|
||||
public static final String SQLITE = "Sqlite";
|
||||
public static final String MYSQL = "Mysql";
|
||||
public static final String ORACLE = "Oracle";
|
||||
public static final String DAMENG = "Dameng";
|
||||
public static final String MASTERBEAN = "masterDataSource";
|
||||
public static final String DYNAMICBEAN = "dynamicDataSource";
|
||||
public static final String PASSWORD = "******";
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.hcframe.base.module.druid;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class DruidAuth {
|
||||
|
||||
private String username="admin";
|
||||
private String password="123456";
|
||||
private String allow = "";
|
||||
private String deny="";
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user