260703_01_FST: First Commit

This commit is contained in:
2026-07-03 16:20:48 +09:00
commit 34b8d41a28
55 changed files with 2127 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
pipeline {
agent none
options {
disableConcurrentBuilds()
timestamps()
}
environment {
AGENT_LABEL = '__AGENT_LABEL__'
REPO_URL = '__REPO_URL__'
BRANCH = '__BRANCH__'
SERVICE_NAME = '__SERVICE_NAME__'
APP_ROOT = '__APP_ROOT__'
}
stages {
stage('Git Pull') {
agent { label "${env.AGENT_LABEL}" }
steps {
deleteDir()
dir('src') {
git branch: env.BRANCH, url: env.REPO_URL
sh '''#!/usr/bin/env bash
set -euo pipefail
echo "[INFO] branch=$(git rev-parse --abbrev-ref HEAD)"
echo "[INFO] commit=$(git rev-parse --short HEAD)"
'''
}
stash name: 'src', includes: 'src/**,src/.*,src/**/.*', excludes: 'src/.git/**'
}
}
stage('Build') {
agent { label "${env.AGENT_LABEL}" }
steps {
deleteDir()
unstash 'src'
dir('src') {
withCredentials([
usernamePassword(
credentialsId: '__MAVEN_CREDENTIAL_ID__',
usernameVariable: 'GITEA_MAVEN_USER',
passwordVariable: 'GITEA_MAVEN_TOKEN'
)
]) {
sh '''#!/usr/bin/env bash
set -euo pipefail
chmod +x gradlew
./gradlew clean bootJar
JAR_FILE="$(find build/libs -maxdepth 1 -type f -name '*.jar' ! -name '*-plain.jar' -print -quit)"
test -n "${JAR_FILE}"
cp "${JAR_FILE}" artifact.jar
ls -lh artifact.jar
'''
}
stash name: 'artifact', includes: 'artifact.jar'
}
}
}
stage('Deploy') {
agent { label "${env.AGENT_LABEL}" }
steps {
deleteDir()
unstash 'artifact'
sh '''#!/usr/bin/env bash
set -euo pipefail
mkdir -p "${APP_ROOT}/releases"
TS="$(date +%Y%m%d_%H%M%S)"
RELEASE_DIR="${APP_ROOT}/releases/${TS}"
mkdir -p "${RELEASE_DIR}"
cp artifact.jar "${RELEASE_DIR}/app.jar"
ln -sfn "${RELEASE_DIR}" "${APP_ROOT}/current"
test -f "${APP_ROOT}/current/app.jar"
ls -1dt "${APP_ROOT}"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf
echo "[INFO] deployed release=${RELEASE_DIR}"
'''
}
}
stage('Service Restart') {
agent { label "${env.AGENT_LABEL}" }
steps {
sh '''#!/usr/bin/env bash
set -euo pipefail
sudo -n /usr/bin/systemctl restart "${SERVICE_NAME}"
sudo -n /usr/bin/systemctl status "${SERVICE_NAME}" --no-pager -l | head -n 80
'''
}
}
}
post {
success {
echo '__PROJECT_NAME__ deployment completed successfully.'
}
failure {
echo '__PROJECT_NAME__ deployment failed.'
}
}
}

View File

@@ -0,0 +1,73 @@
# __PROJECT_NAME__
__DESCRIPTION__
## 기술 구성
- Java 17
- Spring Boot 3.5.7
- `com.kri.common:starter:latest.release`
- JPA + QueryDSL + JdbcTemplate
- EmbeddedId 예제
- MyBatis는 생성 옵션에 따라 포함
## Gitea Maven 인증
Windows 사용자 Gradle 설정:
```text
%USERPROFILE%\.gradle\gradle.properties
```
```properties
giteaUser=사용자명
giteaToken=Gitea토큰
```
또는 다음 환경변수를 사용할 수 있습니다.
```text
GITEA_MAVEN_USER
GITEA_MAVEN_TOKEN
```
## 실행
Windows:
```powershell
.\gradlew.bat bootRun
```
Linux/macOS:
```bash
./gradlew bootRun
```
프로필 지정:
```powershell
.\gradlew.bat bootRun --args="--spring.profiles.active=local"
```
## 빌드
```powershell
.\gradlew.bat clean build
```
## 인증 설정
공용 Starter 설정으로 제어합니다.
```yaml
kri:
security:
enabled: true
auth:
apikey:
enabled: false
```
프로젝트 내부에 JWT/API Key 필터를 중복 구현하지 않습니다.

View File

@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

24
templates/base/_gitignore Normal file
View File

@@ -0,0 +1,24 @@
.gradle/
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/
*.iws
*.iml
*.ipr
out/
### VS Code ###
.vscode/
### Logs / runtime files ###
logs/
upload-file/
*.log
### OS ###
.DS_Store
Thumbs.db

View File

@@ -0,0 +1,95 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.7'
id 'io.spring.dependency-management' version '1.1.7'
}
group = '__BASE_PACKAGE__'
version = '0.0.1-SNAPSHOT'
description = '__DESCRIPTION__'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
def giteaUser = findProperty('giteaUser')
?: System.getenv('GITEA_MAVEN_USER')
?: ''
def giteaToken = findProperty('giteaToken')
?: System.getenv('GITEA_MAVEN_TOKEN')
?: ''
repositories {
mavenCentral()
maven {
name = 'gitea'
url = uri('https://gitea.kric.com/api/packages/KRi/maven')
credentials {
username = giteaUser
password = giteaToken
}
}
}
configurations.configureEach {
resolutionStrategy.cacheDynamicVersionsFor 0, 'seconds'
}
dependencies {
implementation 'com.kri.common:starter:latest.release'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.11'
implementation 'io.github.openfeign.querydsl:querydsl-jpa:7.1'
annotationProcessor 'com.querydsl:querydsl-apt:5.0.0:jakarta'
annotationProcessor 'jakarta.annotation:jakarta.annotation-api'
annotationProcessor 'jakarta.persistence:jakarta.persistence-api'
__DATABASE_DEPENDENCY__
__MYBATIS_DEPENDENCY__
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
__MYBATIS_TEST_DEPENDENCY__
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
def querydslDir = layout.buildDirectory.dir('generated/querydsl').get().asFile
sourceSets {
main.java.srcDirs += [querydslDir]
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.generatedSourceOutputDirectory.set(file(querydslDir))
}
tasks.named('test') {
useJUnitPlatform()
}
tasks.named('clean') {
doLast {
delete querydslDir
}
}

View File

@@ -0,0 +1,16 @@
[Unit]
Description=__PROJECT_NAME__
After=network.target
[Service]
Type=simple
User=jenkins
WorkingDirectory=__APP_ROOT__/current
Environment=SPRING_PROFILES_ACTIVE=prod
ExecStart=/usr/bin/java -jar __APP_ROOT__/current/app.jar
Restart=always
RestartSec=5
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,3 @@
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.caching=true

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
templates/base/gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
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
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
templates/base/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = '__PROJECT_NAME__'

View File

@@ -0,0 +1,14 @@
package __BASE_PACKAGE__;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan
public class __APPLICATION_CLASS__ {
public static void main(String[] args) {
SpringApplication.run(__APPLICATION_CLASS__.class, args);
}
}

View File

@@ -0,0 +1,9 @@
package __BASE_PACKAGE__.common.consts;
public final class ExampleConstant {
public static final int DEFAULT_BATCH_SIZE = 1_000;
private ExampleConstant() {
}
}

View File

@@ -0,0 +1,6 @@
package __BASE_PACKAGE__.common.enums;
public enum ExampleStatus {
ACTIVE,
INACTIVE
}

View File

@@ -0,0 +1,13 @@
package __BASE_PACKAGE__.common.util;
public final class StringNormalizer {
private StringNormalizer() {
}
public static String trimToNull(String value) {
if (value == null) return null;
String normalized = value.trim();
return normalized.isEmpty() ? null : normalized;
}
}

View File

@@ -0,0 +1,4 @@
/**
* 프로젝트 전용 Bean Validation annotation과 validator를 배치합니다.
*/
package __BASE_PACKAGE__.common.validation;

View File

@@ -0,0 +1,14 @@
package __BASE_PACKAGE__.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "kri.file")
public class FileStorageProperties {
private String baseDir = "./upload-file";
private String resourcePattern = "/files/**";
}

View File

@@ -0,0 +1,15 @@
package __BASE_PACKAGE__.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class JdbcConfig {
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}

View File

@@ -0,0 +1,19 @@
package __BASE_PACKAGE__.config;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@RequiredArgsConstructor
public class QueryDSLConfig {
private final EntityManager entityManager;
@Bean
public JPAQueryFactory jpaQueryFactory() {
return new JPAQueryFactory(entityManager);
}
}

View File

@@ -0,0 +1,26 @@
package __BASE_PACKAGE__.config;
import java.nio.file.Path;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
public class WebResourceConfig implements WebMvcConfigurer {
private final FileStorageProperties fileStorageProperties;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String location = Path.of(fileStorageProperties.getBaseDir())
.toAbsolutePath()
.normalize()
.toUri()
.toString();
registry.addResourceHandler(fileStorageProperties.getResourcePattern())
.addResourceLocations(location.endsWith("/") ? location : location + "/");
}
}

View File

@@ -0,0 +1,38 @@
package __BASE_PACKAGE__.controller;
import __BASE_PACKAGE__.dto.request.CreateExampleRequest;
import __BASE_PACKAGE__.dto.response.ExampleResponse;
import __BASE_PACKAGE__.service.ExampleService;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/examples")
public class ExampleController {
private final ExampleService exampleService;
@GetMapping
public List<ExampleResponse> search(
@RequestParam(defaultValue = "") String keyword,
@RequestParam(defaultValue = "20") int limit
) {
return exampleService.search(keyword, limit);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ExampleResponse create(@Valid @RequestBody CreateExampleRequest request) {
return exampleService.create(request);
}
}

View File

@@ -0,0 +1,14 @@
package __BASE_PACKAGE__.controller;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PingController {
@GetMapping("/ping")
public Map<String, String> ping() {
return Map.of("status", "ok");
}
}

View File

@@ -0,0 +1,12 @@
package __BASE_PACKAGE__.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
public record CreateExampleRequest(
@NotNull @Positive Long groupId,
@NotNull @Positive Integer sequence,
@NotBlank String name
) {
}

View File

@@ -0,0 +1,19 @@
package __BASE_PACKAGE__.dto.response;
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
public record ExampleResponse(
Long groupId,
Integer sequence,
String name,
String status
) {
public static ExampleResponse from(ExampleEntity entity) {
return new ExampleResponse(
entity.getId().getGroupId(),
entity.getId().getSequence(),
entity.getName(),
entity.getStatus().name()
);
}
}

View File

@@ -0,0 +1,42 @@
package __BASE_PACKAGE__.persistence.entity;
import __BASE_PACKAGE__.common.enums.ExampleStatus;
import __BASE_PACKAGE__.persistence.entity.id.ExampleEntityId;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Entity
@Table(name = "t_example")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class ExampleEntity {
@EmbeddedId
private ExampleEntityId id;
@Column(name = "name", nullable = false, length = 100)
private String name;
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false, length = 20)
private ExampleStatus status;
@Builder
public ExampleEntity(ExampleEntityId id, String name, ExampleStatus status) {
this.id = id;
this.name = name;
this.status = status == null ? ExampleStatus.ACTIVE : status;
}
public void changeName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,28 @@
package __BASE_PACKAGE__.persistence.entity.id;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import java.io.Serial;
import java.io.Serializable;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Embeddable
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class ExampleEntityId implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Column(name = "group_id", nullable = false)
private Long groupId;
@Column(name = "sequence", nullable = false)
private Integer sequence;
}

View File

@@ -0,0 +1,9 @@
package __BASE_PACKAGE__.persistence.jdbc;
public record ExampleBulkItem(
Long groupId,
Integer sequence,
String name,
String status
) {
}

View File

@@ -0,0 +1,47 @@
package __BASE_PACKAGE__.persistence.jdbc;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
@RequiredArgsConstructor
public class ExampleBulkJdbcRepository {
private final JdbcTemplate jdbcTemplate;
public void insertAll(List<ExampleBulkItem> items, int batchSize) {
if (items == null || items.isEmpty()) return;
String sql = """
insert into t_example (group_id, sequence, name, status)
values (?, ?, ?, ?)
""";
int safeBatchSize = Math.max(batchSize, 1);
for (int from = 0; from < items.size(); from += safeBatchSize) {
int to = Math.min(from + safeBatchSize, items.size());
List<ExampleBulkItem> batch = items.subList(from, to);
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement statement, int index) throws SQLException {
ExampleBulkItem item = batch.get(index);
statement.setLong(1, item.groupId());
statement.setInt(2, item.sequence());
statement.setString(3, item.name());
statement.setString(4, item.status());
}
@Override
public int getBatchSize() {
return batch.size();
}
});
}
}
}

View File

@@ -0,0 +1,11 @@
package __BASE_PACKAGE__.persistence.mapper;
import __BASE_PACKAGE__.dto.response.ExampleResponse;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ExampleMapper {
List<ExampleResponse> findByName(@Param("keyword") String keyword);
}

View File

@@ -0,0 +1,15 @@
package __BASE_PACKAGE__.persistence.query;
import __BASE_PACKAGE__.persistence.entity.QExampleEntity;
import com.querydsl.core.types.dsl.BooleanExpression;
public final class ExamplePredicates {
private ExamplePredicates() {
}
public static BooleanExpression nameContains(QExampleEntity example, String keyword) {
if (keyword == null || keyword.isBlank()) return null;
return example.name.containsIgnoreCase(keyword.trim());
}
}

View File

@@ -0,0 +1,8 @@
package __BASE_PACKAGE__.persistence.repository;
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
import java.util.List;
public interface ExampleQueryRepository {
List<ExampleEntity> findByNameContains(String keyword, int limit);
}

View File

@@ -0,0 +1,25 @@
package __BASE_PACKAGE__.persistence.repository;
import static __BASE_PACKAGE__.persistence.entity.QExampleEntity.exampleEntity;
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
import __BASE_PACKAGE__.persistence.query.ExamplePredicates;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.List;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class ExampleQueryRepositoryImpl implements ExampleQueryRepository {
private final JPAQueryFactory jpaQueryFactory;
@Override
public List<ExampleEntity> findByNameContains(String keyword, int limit) {
return jpaQueryFactory
.selectFrom(exampleEntity)
.where(ExamplePredicates.nameContains(exampleEntity, keyword))
.orderBy(exampleEntity.id.groupId.asc(), exampleEntity.id.sequence.asc())
.limit(Math.max(limit, 1))
.fetch();
}
}

View File

@@ -0,0 +1,9 @@
package __BASE_PACKAGE__.persistence.repository;
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
import __BASE_PACKAGE__.persistence.entity.id.ExampleEntityId;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ExampleRepository
extends JpaRepository<ExampleEntity, ExampleEntityId>, ExampleQueryRepository {
}

View File

@@ -0,0 +1,21 @@
package __BASE_PACKAGE__.scheduler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@ConditionalOnProperty(
prefix = "app.scheduler.example",
name = "enabled",
havingValue = "true"
)
public class ExampleScheduler {
@Scheduled(cron = "${app.scheduler.example.cron:0 0 1 * * *}")
public void execute() {
log.info("Example scheduler executed");
}
}

View File

@@ -0,0 +1,37 @@
package __BASE_PACKAGE__.service;
import __BASE_PACKAGE__.common.enums.ExampleStatus;
import __BASE_PACKAGE__.dto.request.CreateExampleRequest;
import __BASE_PACKAGE__.dto.response.ExampleResponse;
import __BASE_PACKAGE__.persistence.entity.ExampleEntity;
import __BASE_PACKAGE__.persistence.entity.id.ExampleEntityId;
import __BASE_PACKAGE__.persistence.repository.ExampleRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ExampleService {
private final ExampleRepository exampleRepository;
@Transactional
public ExampleResponse create(CreateExampleRequest request) {
ExampleEntity entity = ExampleEntity.builder()
.id(new ExampleEntityId(request.groupId(), request.sequence()))
.name(request.name())
.status(ExampleStatus.ACTIVE)
.build();
return ExampleResponse.from(exampleRepository.save(entity));
}
public List<ExampleResponse> search(String keyword, int limit) {
return exampleRepository.findByNameContains(keyword == null ? "" : keyword, limit)
.stream()
.map(ExampleResponse::from)
.toList();
}
}

View File

@@ -0,0 +1,10 @@
spring:
datasource:
url: "${DB_URL}"
username: "${DB_USERNAME}"
password: "${DB_PASSWORD}"
driver-class-name: __DATABASE_DRIVER__
logging:
level:
org.hibernate.SQL: DEBUG

View File

@@ -0,0 +1,6 @@
spring:
datasource:
url: "${DB_URL:__DATABASE_LOCAL_URL__}"
username: "${DB_USERNAME:sample}"
password: "${DB_PASSWORD:sample}"
driver-class-name: __DATABASE_DRIVER__

View File

@@ -0,0 +1,10 @@
spring:
datasource:
url: "${DB_URL}"
username: "${DB_USERNAME}"
password: "${DB_PASSWORD}"
driver-class-name: __DATABASE_DRIVER__
kri:
swagger:
enabled: ${KRI_SWAGGER_ENABLED:false}

View File

@@ -0,0 +1,71 @@
server:
port: __PORT__
forward-headers-strategy: framework
spring:
application:
name: __PROJECT_NAME__
profiles:
default: local
jpa:
open-in-view: false
hibernate:
ddl-auto: none
properties:
hibernate:
jdbc:
batch_size: 1000
order_inserts: true
order_updates: true
format_sql: true
servlet:
multipart:
max-file-size: 20MB
max-request-size: 20MB
logging:
file:
path: ./logs
kri:
auth:
apikey:
enabled: ${KRI_API_KEY_ENABLED:false}
key: ${KRI_API_KEY:}
header-name: ${KRI_API_KEY_HEADER_NAME:X-API-Key}
service-code: ${KRI_API_KEY_SERVICE_CODE:__PROJECT_NAME__}
preload-on-startup: ${KRI_API_KEY_PRELOAD_ON_STARTUP:false}
admin-api-enabled: ${KRI_API_KEY_ADMIN_ENABLED:false}
admin-allow-ips: []
security:
enabled: ${KRI_SECURITY_ENABLED:true}
public-paths:
- /v3/api-docs/**
- /swagger-ui.html
- /swagger-ui/**
- /ping
- /files/**
swagger:
enabled: ${KRI_SWAGGER_ENABLED:true}
title: "__PROJECT_NAME__ API"
description: "__DESCRIPTION__"
version: "v1.0.0"
base-package: "__BASE_PACKAGE__"
allowed-ips: []
file:
base-dir: ${FILE_STORAGE_BASE_DIR:./upload-file}
resource-pattern: /files/**
web:
enabled: true
redis:
enabled: false
scheduling:
enabled: true
app:
scheduler:
example:
enabled: ${EXAMPLE_SCHEDULER_ENABLED:false}
cron: ${EXAMPLE_SCHEDULER_CRON:0 0 1 * * *}
__MYBATIS_CONFIG__

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="__BASE_PACKAGE__.persistence.mapper.ExampleMapper">
<select id="findByName" resultType="__BASE_PACKAGE__.dto.response.ExampleResponse">
select
group_id as groupId,
sequence,
name,
status
from t_example
where name like concat('%', #{keyword}, '%')
order by group_id, sequence
</select>
</mapper>

View File

@@ -0,0 +1,13 @@
package __BASE_PACKAGE__;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class PackageStructureTest {
@Test
void templateIsGenerated() {
assertTrue(true);
}
}