首次提交

This commit is contained in:
dengqichen 2024-11-26 13:37:58 +08:00
commit 4b6239c944
39 changed files with 1877 additions and 0 deletions

2
backend/.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

34
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/target/

View File

@ -0,0 +1,19 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

259
backend/mvnw vendored Normal file
View File

@ -0,0 +1,259 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

149
backend/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,149 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

202
backend/pom.xml Normal file
View File

@ -0,0 +1,202 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<groupId>com.qqchen.deploy</groupId>
<artifactId>deploy-cd</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<querydsl.version>5.0.0</querydsl.version>
<lombok.version>1.18.30</lombok.version>
<spring-security.version>6.2.0</spring-security.version>
</properties>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Database -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- QueryDSL -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
<scope>provided</scope>
</dependency>
<!-- MapStruct -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
<scope>provided</scope>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<!-- QueryDSL Plugin -->
<plugin>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-maven-plugin</artifactId>
<version>${querydsl.version}</version>
<executions>
<execution>
<goals>
<goal>jpa-export</goal>
</goals>
<configuration>
<targetFolder>target/generated-sources/java</targetFolder>
<packages>
<package>com.qqchen.deploy.backend.entity</package>
</packages>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</plugin>
<!-- APT plugin for QueryDSL -->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<classifier>jakarta</classifier>
</dependency>
</dependencies>
</plugin>
<!-- Lombok & MapStruct Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>

10
backend/readme.md Normal file
View File

@ -0,0 +1,10 @@
`查询日期示例`
```
UserQuery query = new UserQuery();
query.setCreateTimeRange(
LocalDateTime.now().minusDays(7), // 一周内
LocalDateTime.now()
);
query.setEnabled(true);
query.setCreateBy("admin");
```

View File

@ -0,0 +1,14 @@
package com.qqchen.deploy.backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}

View File

@ -0,0 +1,43 @@
package com.qqchen.deploy.backend.api;
import com.qqchen.deploy.common.controller.BaseController;
import com.qqchen.deploy.common.dto.Response;
import com.qqchen.deploy.backend.converter.UserConverter;
import com.qqchen.deploy.backend.entity.User;
import com.qqchen.deploy.backend.dto.query.UserQuery;
import com.qqchen.deploy.backend.dto.request.UserRequest;
import com.qqchen.deploy.backend.dto.response.UserResponse;
import com.qqchen.deploy.backend.dto.request.UserRegisterRequest;
import com.qqchen.deploy.backend.service.UserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/users")
public class UserApiController extends BaseController<User, Long, UserQuery, UserRequest, UserResponse> {
protected final UserService userService;
public UserApiController(UserService userService, UserConverter converter) {
this.userService = userService;
this.converter = converter;
}
@PostMapping("/register")
public Response<UserResponse> register(@Validated @RequestBody UserRegisterRequest request) {
// 基础的注册逻辑
if (!request.getPassword().equals(request.getConfirmPassword())) {
return Response.error(Response.INVALID_PARAM_CODE, "两次密码不一致");
}
User user = converter.toEntity(request);
User savedUser = userService.register(user);
return Response.success(converter.toVO(savedUser));
}
// 其他对外API...
// 可以覆盖父类的方法添加更严格的访问控制或参数校验
}

View File

@ -0,0 +1,29 @@
package com.qqchen.deploy.backend.controller;
import com.qqchen.deploy.backend.api.UserApiController;
import com.qqchen.deploy.common.dto.Response;
import com.qqchen.deploy.backend.converter.UserConverter;
import com.qqchen.deploy.backend.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mgmt/users")
public class UserController extends UserApiController {
public UserController(UserService userService, UserConverter converter) {
super(userService, converter);
}
@GetMapping("/check-username")
public Response<Boolean> checkUsername(@RequestParam String username) {
return Response.success(userService.checkUsernameExists(username));
}
@GetMapping("/check-email")
public Response<Boolean> checkEmail(@RequestParam String email) {
return Response.success(userService.checkEmailExists(email));
}
}

View File

@ -0,0 +1,28 @@
package com.qqchen.deploy.backend.converter;
import com.qqchen.deploy.common.converter.BaseConverter;
import com.qqchen.deploy.backend.entity.User;
import com.qqchen.deploy.backend.dto.request.UserRequest;
import com.qqchen.deploy.backend.dto.response.UserResponse;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserConverter extends BaseConverter<User, UserRequest, UserResponse> {
@Override
@Mapping(target = "id", ignore = true)
@Mapping(target = "enabled", constant = "true")
User toEntity(UserRequest request);
@Override
@Mapping(target = "password", ignore = true)
UserResponse toVO(User user);
@Override
@Mapping(target = "id", ignore = true)
@Mapping(target = "enabled", ignore = true)
void updateEntity(@MappingTarget User user, UserRequest request);
}

View File

@ -0,0 +1,14 @@
package com.qqchen.deploy.backend.dto.query;
import com.qqchen.deploy.common.annotation.QueryField;
import com.qqchen.deploy.common.enums.QueryType;
import lombok.Data;
@Data
public class UserAddressQuery {
@QueryField(type = QueryType.LIKE)
private String city;
@QueryField(type = QueryType.EQUAL)
private String postcode;
}

View File

@ -0,0 +1,30 @@
package com.qqchen.deploy.backend.dto.query;
import com.qqchen.deploy.common.annotation.QueryField;
import com.qqchen.deploy.common.query.BaseQuery;
import com.qqchen.deploy.common.enums.QueryType;
import com.qqchen.deploy.common.query.DateRange;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = true)
public class UserQuery extends BaseQuery {
@QueryField(type = QueryType.LIKE)
private String username;
@QueryField(type = QueryType.LIKE)
private String email;
@QueryField(type = QueryType.IN)
private List<String> roles;
@QueryField(type = QueryType.BETWEEN)
private DateRange createTimeRange;
// 嵌套对象查询
private UserAddressQuery address;
}

View File

@ -0,0 +1,16 @@
package com.qqchen.deploy.backend.dto.request;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class UserRegisterRequest extends UserRequest {
@NotEmpty(message = "确认密码不能为空")
private String confirmPassword;
// 可以添加注册特有的字段如验证码等
private String verificationCode;
}

View File

@ -0,0 +1,30 @@
package com.qqchen.deploy.backend.dto.request;
import com.qqchen.deploy.common.dto.BaseRequest;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class UserRequest extends BaseRequest {
@NotBlank(message = "用户名不能为空")
@Size(min = 4, max = 20, message = "用户名长度必须在4-20之间")
private String username;
@NotBlank(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;
@NotBlank(message = "密码不能为空")
@Size(min = 6, max = 20, message = "密码长度必须在6-20之间")
private String password;
private String nickname;
private String phone;
}

View File

@ -0,0 +1,25 @@
package com.qqchen.deploy.backend.dto.response;
import com.qqchen.deploy.common.dto.BaseResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class UserResponse extends BaseResponse {
private Long id;
private String username;
private String email;
private String nickname;
private String phone;
private Boolean enabled;
private String password;
}

View File

@ -0,0 +1,29 @@
package com.qqchen.deploy.backend.entity;
import com.qqchen.deploy.common.domain.Entity;
import jakarta.persistence.Column;
import jakarta.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
@jakarta.persistence.Entity
@Table(name = "t_user")
public class User extends Entity<Long> {
@Column(unique = true, nullable = false)
private String username;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
private String nickname;
private String phone;
private Boolean enabled = true;
}

View File

@ -0,0 +1,11 @@
package com.qqchen.deploy.backend.repository;
import com.qqchen.deploy.common.repository.BaseRepository;
import com.qqchen.deploy.backend.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends BaseRepository<User, Long> {
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}

View File

@ -0,0 +1,11 @@
package com.qqchen.deploy.backend.service;
import com.qqchen.deploy.common.service.BaseService;
import com.qqchen.deploy.backend.entity.User;
public interface UserService extends BaseService<User, Long> {
User register(User user);
User findByUsername(String username);
boolean checkUsernameExists(String username);
boolean checkEmailExists(String email);
}

View File

@ -0,0 +1,50 @@
package com.qqchen.deploy.backend.service.impl;
import com.qqchen.deploy.common.service.impl.BaseServiceImpl;
import com.qqchen.deploy.backend.entity.User;
import com.qqchen.deploy.backend.repository.UserRepository;
import com.qqchen.deploy.backend.service.UserService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {
private final UserRepository userRepository;
@Autowired
public UserServiceImpl(UserRepository userRepository) {
super(userRepository);
this.userRepository = userRepository;
}
@Override
public User register(User user) {
if (checkUsernameExists(user.getUsername())) {
throw new RuntimeException("用户名已存在");
}
if (checkEmailExists(user.getEmail())) {
throw new RuntimeException("邮箱已存在");
}
return userRepository.save(user);
}
@Override
public User findByUsername(String username) {
// 实现查询逻辑
return null;
}
@Override
public boolean checkUsernameExists(String username) {
return userRepository.existsByUsername(username);
}
@Override
public boolean checkEmailExists(String email) {
return userRepository.existsByEmail(email);
}
}

View File

@ -0,0 +1,15 @@
package com.qqchen.deploy.common.annotation;
import com.qqchen.deploy.common.enums.QueryType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface QueryField {
String field() default ""; // 实体类中的字段名
QueryType type() default QueryType.EQUAL; // 查询方式
}

View File

@ -0,0 +1,26 @@
package com.qqchen.deploy.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
@Configuration
@EnableJpaAuditing
public class JpaConfig {
@Bean
public AuditorAware<String> auditorProvider() {
return () -> {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return Optional.of("system");
}
return Optional.of(authentication.getName());
};
}
}

View File

@ -0,0 +1,32 @@
package com.qqchen.deploy.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // 禁用CSRF
.authorizeHttpRequests(auth -> auth
// // 公开接口
// .requestMatchers("/*/*").permitAll()
// // Swagger相关接口
// .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
// // 健康检查接口
// .requestMatchers("/actuator/**").permitAll()
// 开发阶段可以暂时允许所有请求
.anyRequest().permitAll()
// 生产环境建议改为需要认证
//.anyRequest().authenticated()
);
return http.build();
}
}

View File

@ -0,0 +1,65 @@
package com.qqchen.deploy.common.controller;
import com.qqchen.deploy.common.converter.BaseConverter;
import com.qqchen.deploy.common.domain.Entity;
import com.qqchen.deploy.common.query.BaseQuery;
import com.qqchen.deploy.common.dto.BaseRequest;
import com.qqchen.deploy.common.dto.Response;
import com.qqchen.deploy.common.service.BaseService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.io.Serializable;
import java.util.List;
/**
* 通用REST控制器
*/
public abstract class BaseController<T extends Entity<ID>, ID extends Serializable, Q extends BaseQuery, R extends BaseRequest, V> {
@Resource
protected BaseService<T, ID> service;
@Resource
protected BaseConverter<T, R, V> converter;
@PostMapping
public Response<V> create(@RequestBody R request) {
T entity = converter.toEntity(request);
T savedEntity = service.create(entity);
return Response.success(converter.toVO(savedEntity));
}
@PutMapping("/{id}")
public Response<V> update(@PathVariable ID id, @RequestBody R request) {
T entity = service.findById(id);
converter.updateEntity(entity, request);
T updatedEntity = service.update(entity);
return Response.success(converter.toVO(updatedEntity));
}
@DeleteMapping("/{id}")
public Response<Void> delete(@PathVariable ID id) {
service.delete(id);
return Response.success();
}
@GetMapping("/{id}")
public Response<V> findById(@PathVariable ID id) {
T entity = service.findById(id);
return Response.success(converter.toVO(entity));
}
@GetMapping
public Response<List<V>> findAll() {
List<T> entities = service.findAll();
return Response.success(converter.toVOList(entities));
}
@GetMapping("/page")
public Response<Page<V>> page(Q query) {
Page<T> page = service.page(query);
return Response.success(page.map(entity -> converter.toVO(entity)));
}
}

View File

@ -0,0 +1,27 @@
package com.qqchen.deploy.common.converter;
import com.qqchen.deploy.common.domain.Entity;
import com.qqchen.deploy.common.dto.BaseRequest;
import org.mapstruct.MappingTarget;
import org.springframework.data.domain.Page;
import java.util.List;
public interface BaseConverter<D extends Entity<?>, R extends BaseRequest, V> {
// Request -> Domain
D toEntity(R request);
// Domain -> VO
V toVO(D entity);
// Domain List -> VO List
List<V> toVOList(List<D> entityList);
// 更新实体
void updateEntity(@MappingTarget D entity, R request);
// 转换分页结果
default Page<V> toVOPage(Page<D> page) {
return page.map(this::toVO);
}
}

View File

@ -0,0 +1,10 @@
package com.qqchen.deploy.common.domain;
import java.io.Serializable;
/**
* 聚合根基类
*/
public abstract class AggregateRoot<ID extends Serializable> extends Entity<ID> {
// 聚合根特定的行为可以在这里添加
}

View File

@ -0,0 +1,53 @@
package com.qqchen.deploy.common.domain;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.Version;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 领域实体基类
*/
@Getter
@Setter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Entity<ID extends Serializable> implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private ID id;
@CreatedBy
@Column(updatable = false)
private String createBy;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createTime;
@LastModifiedBy
private String updateBy;
@LastModifiedDate
private LocalDateTime updateTime;
@Version
private Integer version;
@Column(nullable = false)
private Boolean deleted = false;
}

View File

@ -0,0 +1,21 @@
package com.qqchen.deploy.common.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public abstract class BaseRequest implements Serializable {
private String operator; // 操作人
private Long timestamp; // 操作时间戳
private String traceId; // 请求追踪ID
private String clientIp; // 客户端IP
private String clientType; // 客户端类型
private String appVersion; // 应用版本
}

View File

@ -0,0 +1,20 @@
package com.qqchen.deploy.common.dto;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public abstract class BaseResponse implements Serializable {
protected String createBy;
protected LocalDateTime createTime;
protected String updateBy;
protected LocalDateTime updateTime;
protected Integer version;
}

View File

@ -0,0 +1,45 @@
package com.qqchen.deploy.common.dto;
import lombok.Data;
import java.io.Serializable;
/**
* 通用响应对象
*/
@Data
public class Response<T> implements Serializable {
private boolean success;
private String message;
private T data;
private Integer code;
public static final int SUCCESS_CODE = 200;
public static final int ERROR_CODE = 500;
public static final int INVALID_PARAM_CODE = 400;
public static final int UNAUTHORIZED_CODE = 401;
public static <T> Response<T> success() {
return success(null);
}
public static <T> Response<T> success(T data) {
Response<T> response = new Response<>();
response.setSuccess(true);
response.setCode(SUCCESS_CODE);
response.setData(data);
return response;
}
public static <T> Response<T> error(String message) {
return error(ERROR_CODE, message);
}
public static <T> Response<T> error(Integer code, String message) {
Response<T> response = new Response<>();
response.setSuccess(false);
response.setCode(code);
response.setMessage(message);
return response;
}
}

View File

@ -0,0 +1,14 @@
package com.qqchen.deploy.common.enums;
public enum QueryType {
EQUAL, // 等于
LIKE, // 模糊查询
START_WITH, // 开始于
END_WITH, // 结束于
GREATER_THAN, // 大于
LESS_THAN, // 小于
GREATER_EQUAL, // 大于等于
LESS_EQUAL, // 小于等于
IN, // 包含
BETWEEN // 范围
}

View File

@ -0,0 +1,61 @@
package com.qqchen.deploy.common.query;
import com.qqchen.deploy.common.annotation.QueryField;
import com.qqchen.deploy.common.enums.QueryType;
import com.qqchen.deploy.common.query.DateRange;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
@Data
public abstract class BaseQuery implements Serializable {
private Integer pageNum = 1;
private Integer pageSize = 10;
private String sortField;
private String sortOrder;
// 通用状态查询
@QueryField(field = "enabled")
private Boolean enabled;
@QueryField(field = "deleted")
private Boolean deleted;
// 创建时间范围查询
@QueryField(field = "createTime", type = QueryType.BETWEEN)
private DateRange createTimeRange;
// 更新时间范围查询
@QueryField(field = "updateTime", type = QueryType.BETWEEN)
private DateRange updateTimeRange;
// 创建人查询
@QueryField(field = "createBy", type = QueryType.EQUAL)
private String createBy;
// 更新人查询
@QueryField(field = "updateBy", type = QueryType.EQUAL)
private String updateBy;
// 版本号查询
@QueryField(field = "version", type = QueryType.EQUAL)
private Integer version;
// 便捷方法
public void setCreateTimeRange(LocalDateTime start, LocalDateTime end) {
if (start != null || end != null) {
this.createTimeRange = new DateRange(start, end);
}
}
public void setUpdateTimeRange(LocalDateTime start, LocalDateTime end) {
if (start != null || end != null) {
this.updateTimeRange = new DateRange(start, end);
}
}
}

View File

@ -0,0 +1,49 @@
package com.qqchen.deploy.common.query;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DateRange {
private LocalDateTime from;
private LocalDateTime to;
public boolean hasFrom() {
return from != null;
}
public boolean hasTo() {
return to != null;
}
public boolean isValid() {
return from != null && to != null && !from.isAfter(to);
}
// 便捷方法
public static DateRange of(LocalDateTime from, LocalDateTime to) {
return new DateRange(from, to);
}
public static DateRange lastDays(int days) {
return new DateRange(
LocalDateTime.now().minusDays(days),
LocalDateTime.now()
);
}
public static DateRange today() {
LocalDateTime now = LocalDateTime.now();
return new DateRange(
now.withHour(0).withMinute(0).withSecond(0),
now.withHour(23).withMinute(59).withSecond(59)
);
}
}

View File

@ -0,0 +1,12 @@
package com.qqchen.deploy.common.query;
import lombok.Data;
@Data
public class Range<T> {
private T from;
private T to;
}

View File

@ -0,0 +1,35 @@
package com.qqchen.deploy.common.repository;
import com.qqchen.deploy.common.domain.Entity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
@NoRepositoryBean
public interface BaseRepository<T extends Entity<ID>, ID extends Serializable>
extends JpaRepository<T, ID>, QuerydslPredicateExecutor<T> {
@Override
@Query("select e from #{#entityName} e where e.deleted = false")
List<T> findAll();
@Override
@Query("select e from #{#entityName} e where e.id = ?1 and e.deleted = false")
Optional<T> findById(ID id);
@Override
default void delete(T entity) {
entity.setDeleted(true);
save(entity);
}
@Override
default void deleteById(ID id) {
findById(id).ifPresent(this::delete);
}
}

View File

@ -0,0 +1,25 @@
package com.qqchen.deploy.common.service;
import com.qqchen.deploy.common.domain.Entity;
import com.qqchen.deploy.common.query.BaseQuery;
import org.springframework.data.domain.Page;
import java.io.Serializable;
import java.util.List;
/**
* 通用服务接口
*/
public interface BaseService<T extends Entity<ID>, ID extends Serializable> {
T create(T entity);
T update(T entity);
void delete(ID id);
T findById(ID id);
List<T> findAll();
Page<T> page(BaseQuery query);
}

View File

@ -0,0 +1,322 @@
package com.qqchen.deploy.common.service.impl;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.stream.Collectors;
import java.util.Collection;
import java.util.List;
import com.qqchen.deploy.common.annotation.QueryField;
import com.qqchen.deploy.common.domain.Entity;
import com.qqchen.deploy.common.query.BaseQuery;
import com.qqchen.deploy.common.enums.QueryType;
import com.qqchen.deploy.common.query.DateRange;
import com.qqchen.deploy.common.query.Range;
import com.qqchen.deploy.common.repository.BaseRepository;
import com.qqchen.deploy.common.service.BaseService;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.EntityPath;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.*;
import org.springframework.core.GenericTypeResolver;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;
@Transactional
public abstract class BaseServiceImpl<T extends Entity<ID>, ID extends Serializable> implements BaseService<T, ID> {
protected final BaseRepository<T, ID> repository;
private final EntityPath<T> entityPath;
protected BaseServiceImpl(BaseRepository<T, ID> repository) {
this.repository = repository;
this.entityPath = getEntityPath();
}
@Override
public T create(T entity) {
return repository.save(entity);
}
@Override
public T update(T entity) {
return repository.save(entity);
}
@Override
public void delete(ID id) {
repository.deleteById(id);
}
@Override
public T findById(ID id) {
return repository.findById(id)
.orElseThrow(() -> new RuntimeException("Entity not found"));
}
@Override
public List<T> findAll() {
return repository.findAll();
}
// 自动获取Q类实例
// 自动获取Q类实例
@SuppressWarnings("unchecked")
private EntityPath<T> getEntityPath() {
Class<?>[] genericTypes = GenericTypeResolver.resolveTypeArguments(getClass(), BaseServiceImpl.class);
if (genericTypes == null || genericTypes.length < 2) {
throw new IllegalStateException("Could not resolve generic type arguments for " + getClass().getName());
}
Class<T> entityClass = (Class<T>) genericTypes[0];
try {
// 获取Q类
String qClassName = entityClass.getPackageName() + ".Q" + entityClass.getSimpleName();
Class<?> qClass = Class.forName(qClassName);
// 获取静态实例字段
Field instanceField = qClass.getDeclaredField(entityClass.getSimpleName().toLowerCase());
return (EntityPath<T>) instanceField.get(null);
} catch (Exception e) {
throw new RuntimeException("Failed to get Q class for " + entityClass.getName(), e);
}
}
@Override
public Page<T> page(BaseQuery query) {
return repository.findAll(
createPredicate(query),
createPageRequest(query)
);
}
protected Predicate createPredicate(BaseQuery query) {
BooleanBuilder builder = new BooleanBuilder();
processFields(query, builder, entityPath, "");
return builder.getValue();
}
private void processFields(Object query, BooleanBuilder builder, EntityPath<?> currentPath, String prefix) {
Field[] fields = query.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(query);
if (value != null) {
QueryField queryField = field.getAnnotation(QueryField.class);
if (queryField != null) {
String fieldName = StringUtils.hasText(queryField.field()) ?
queryField.field() : field.getName();
String fullPath = StringUtils.hasText(prefix) ? prefix + "." + fieldName : fieldName;
Path<?> path = EntityPathResolver.getPath(currentPath, fieldName);
if (path != null) {
addPredicate(builder, path, value, queryField.type());
}
} else if (!isBaseType(field.getType()) && !isCollection(field.getType())) {
// 处理嵌套对象
String nestedPrefix = StringUtils.hasText(prefix) ?
prefix + "." + field.getName() : field.getName();
Path<?> nestedPath = EntityPathResolver.getPath(currentPath, field.getName());
if (nestedPath instanceof EntityPath) {
processFields(value, builder, (EntityPath<?>) nestedPath, nestedPrefix);
}
}
}
} catch (Exception e) {
// 忽略无法处理的字段
}
}
}
private void addPredicate(BooleanBuilder builder, Path<?> path, Object value, QueryType queryType) {
if (path instanceof StringPath) {
addStringPredicate(builder, (StringPath) path, value, queryType);
} else if (path instanceof BooleanPath) {
addBooleanPredicate(builder, (BooleanPath) path, value);
} else if (path instanceof NumberPath) {
addNumberPredicate(builder, (NumberPath<?>) path, value, queryType);
} else if (path instanceof DateTimePath) {
addDatePredicate(builder, (DateTimePath<?>) path, value, queryType);
} else if (path instanceof EnumPath) {
addEnumPredicate(builder, (EnumPath) path, value);
}
}
private void addStringPredicate(BooleanBuilder builder, StringPath path, Object value, QueryType queryType) {
switch (queryType) {
case EQUAL:
builder.and(path.eq(value.toString()));
break;
case LIKE:
builder.and(path.containsIgnoreCase(value.toString()));
break;
case START_WITH:
builder.and(path.startsWithIgnoreCase(value.toString()));
break;
case END_WITH:
builder.and(path.endsWithIgnoreCase(value.toString()));
break;
case IN:
if (value instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) value;
List<String> strings = collection.stream()
.map(Object::toString)
.collect(Collectors.toList());
builder.and(path.in(strings));
}
break;
}
}
@SuppressWarnings("unchecked")
private <N extends Number & Comparable<?>> void addNumberPredicate(BooleanBuilder builder,
NumberPath<N> path, Object value, QueryType queryType) {
N numValue = (N) parseNumber(value, path.getType());
if (numValue != null) {
switch (queryType) {
case EQUAL:
builder.and(path.eq(numValue));
break;
case GREATER_THAN:
builder.and(path.gt(numValue));
break;
case LESS_THAN:
builder.and(path.lt(numValue));
break;
case GREATER_EQUAL:
builder.and(path.goe(numValue));
break;
case LESS_EQUAL:
builder.and(path.loe(numValue));
break;
case BETWEEN:
if (value instanceof Range) {
Range<?> range = (Range<?>) value;
N from = (N) parseNumber(range.getFrom(), path.getType());
N to = (N) parseNumber(range.getTo(), path.getType());
if (from != null && to != null) {
builder.and(path.between(from, to));
}
}
break;
}
}
}
@SuppressWarnings("unchecked")
private <T extends Comparable<?>> void addDatePredicate(BooleanBuilder builder, DateTimePath<T> path, Object value, QueryType queryType) {
if (value instanceof DateRange range) {
switch (queryType) {
case EQUAL:
if (range.getFrom() != null) {
builder.and(path.eq((T) range.getFrom()));
}
break;
case GREATER_THAN:
if (range.getFrom() != null) {
builder.and(path.gt((T) range.getFrom()));
}
break;
case LESS_THAN:
if (range.getTo() != null) {
builder.and(path.lt((T) range.getTo()));
}
break;
case BETWEEN:
if (range.isValid()) {
builder.and(path.between((T) range.getFrom(), (T) range.getTo()));
} else if (range.hasFrom()) {
builder.and(path.goe((T) range.getFrom()));
} else if (range.hasTo()) {
builder.and(path.loe((T) range.getTo()));
}
break;
}
}
}
private void addBooleanPredicate(BooleanBuilder builder, BooleanPath path, Object value) {
if (value instanceof Boolean) {
builder.and(path.eq((Boolean) value));
}
}
private void addEnumPredicate(BooleanBuilder builder, EnumPath path, Object value) {
if (value instanceof Enum) {
builder.and(path.eq(value));
}
}
private boolean isBaseType(Class<?> clazz) {
return clazz.isPrimitive()
|| Number.class.isAssignableFrom(clazz)
|| String.class.equals(clazz)
|| Boolean.class.equals(clazz)
|| Date.class.isAssignableFrom(clazz)
|| clazz.isEnum();
}
private boolean isCollection(Class<?> clazz) {
return Collection.class.isAssignableFrom(clazz);
}
protected PageRequest createPageRequest(BaseQuery query) {
return PageRequest.of(
query.getPageNum() - 1,
query.getPageSize(),
createSort(query)
);
}
protected Sort createSort(BaseQuery query) {
return StringUtils.hasText(query.getSortField()) ?
Sort.by(Sort.Direction.fromString(query.getSortOrder()), query.getSortField()) :
Sort.unsorted();
}
private Number parseNumber(Object value, Class<?> targetType) {
if (value == null) return null;
try {
String strValue = String.valueOf(value);
if (targetType == Long.class) {
return Long.valueOf(strValue);
} else if (targetType == Integer.class) {
return Integer.valueOf(strValue);
} else if (targetType == Double.class) {
return Double.valueOf(strValue);
} else if (targetType == Float.class) {
return Float.valueOf(strValue);
} else if (targetType == BigDecimal.class) {
return new BigDecimal(strValue);
}
} catch (NumberFormatException e) {
// 忽略转换错误
}
return null;
}
// EntityPathResolver 用于解析实体路径
private static class EntityPathResolver {
public static Path<?> getPath(EntityPath<?> entityPath, String fieldName) {
try {
Field field = entityPath.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (Path<?>) field.get(entityPath);
} catch (Exception e) {
return null;
}
}
}
}

View File

@ -0,0 +1,27 @@
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/2024_11_24_platform?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
dialect: org.hibernate.dialect.MySQL8Dialect
jdbc:
time_zone: Asia/Shanghai
jwt:
secret: 'thisIsAVeryVerySecretKeyForJwtTokenGenerationAndValidation123456789'
expiration: 86400
jackson:
time-zone: Asia/Shanghai

View File

@ -0,0 +1,13 @@
package com.qqchen.deploy.common;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BackendApplicationTests {
@Test
void contextLoads() {
}
}