Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d173ebdab | ||
|
|
43898296d1 | ||
|
|
ea8b6591c2 | ||
|
|
14ae167d61 | ||
|
|
9dddb11baf | ||
|
|
2c210e6657 | ||
|
|
c7dc979193 | ||
|
|
17014bcb67 | ||
|
|
4a409b63d7 | ||
|
|
12007bd3ea | ||
|
|
743b7c1c6a | ||
|
|
499b51d2e1 | ||
|
|
51875bcc5e | ||
|
|
51545137be | ||
|
|
0dd5c03d7d |
14
.gitignore
vendored
14
.gitignore
vendored
@@ -1,14 +0,0 @@
|
||||
# ---> VisualStudioCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
3
.idea/.gitignore
generated
vendored
Normal file
3
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
9
.idea/internetDev.iml
generated
Normal file
9
.idea/internetDev.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/misc.xml
generated
Normal file
6
.idea/misc.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="21" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/internetDev.iml" filepath="$PROJECT_DIR$/.idea/internetDev.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
Binary file not shown.
38
catalog.html
38
catalog.html
@@ -1,38 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<head>
|
||||
<title>Каталог</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h3>Тут разбита музыка на жанры</h3>
|
||||
<p>Инфа будет +- такая</p>
|
||||
<div class="list">
|
||||
<ul class="punk-list">
|
||||
<li>
|
||||
<div class="item">
|
||||
<img class="catalog" src="pankrock.jpg" alt="Панк-Рок" width=200>
|
||||
<a href="punkrock.html">Панк-Рок</a>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div class="item">
|
||||
<img class="catalog" src="psy.png" alt="Психоделический рок" width=200>
|
||||
<a href="">Психоделика</a>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<div class="item">
|
||||
<img class="catalog" src="garajnipunk.jpg" alt="Гаражный-панк" width=200>
|
||||
<a href="">Гражный-панк</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<a href="index.html"> Вернуться назад</a>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
3
demo/.gitattributes
vendored
Normal file
3
demo/.gitattributes
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
37
demo/.gitignore
vendored
Normal file
37
demo/.gitignore
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
50
demo/build.front.gradle
Normal file
50
demo/build.front.gradle
Normal file
@@ -0,0 +1,50 @@
|
||||
apply plugin: "com.github.node-gradle.node"
|
||||
|
||||
logger.quiet("Configure front builder")
|
||||
|
||||
ext {
|
||||
frontDir = file("${project.projectDir}/punkrock-react")
|
||||
staticDir = file("${project.projectDir}/src/main/resources/static")
|
||||
if (!frontDir.exists()) {
|
||||
throw new GradleException("Frontend app directory is not exists")
|
||||
}
|
||||
logger.quiet("Webapp dir is {}", frontDir.toString())
|
||||
}
|
||||
|
||||
node {
|
||||
version = "22.17.1"
|
||||
npmVersion = "10.9.2"
|
||||
download = true
|
||||
}
|
||||
|
||||
tasks.register("frontDepsInstall", NpmTask) {
|
||||
group = "front"
|
||||
description = "Installs dependencies from package.json"
|
||||
logger.quiet(description)
|
||||
workingDir = frontDir
|
||||
args = ["install"]
|
||||
}
|
||||
|
||||
tasks.register("frontBuild", NpmTask) {
|
||||
group = "front"
|
||||
description = "Build frontend webapp"
|
||||
logger.quiet(description)
|
||||
workingDir = frontDir
|
||||
dependsOn frontDepsInstall
|
||||
args = ["run", "build"]
|
||||
}
|
||||
|
||||
tasks.register("copyFrontend", org.gradle.api.tasks.Copy) {
|
||||
group = "front"
|
||||
description = "Copy built frontend to static resources"
|
||||
dependsOn frontBuild
|
||||
from("${frontDir}/build")
|
||||
into(staticDir)
|
||||
includeEmptyDirs = false
|
||||
}
|
||||
|
||||
if (frontDir.exists()) {
|
||||
processResources.dependsOn copyFrontend
|
||||
bootJar.dependsOn copyFrontend
|
||||
}
|
||||
|
||||
103
demo/build.gradle
Normal file
103
demo/build.gradle
Normal file
@@ -0,0 +1,103 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.5'
|
||||
id 'io.spring.dependency-management' version '1.1.5'
|
||||
id 'com.github.node-gradle.node' version '7.1.0' apply false
|
||||
id 'org.liquibase.gradle' version '2.2.2' apply false
|
||||
}
|
||||
|
||||
group = 'com.example'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
description = 'Demo project for Spring Boot'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
ext {
|
||||
springdocVersion = "2.2.0"
|
||||
h2Version = "2.4.240"
|
||||
postgresVersion = "42.7.8"
|
||||
liquibaseVersion = "4.33.0"
|
||||
thymeleafLayoutVersion = "3.4.0"
|
||||
bootstrapVersion = "5.3.3"
|
||||
bootstrapIconsVersion = "1.11.3"
|
||||
|
||||
springProfiles = []
|
||||
if (project.hasProperty("front")) {
|
||||
springProfiles.add("front")
|
||||
}
|
||||
if (project.hasProperty("prod")) {
|
||||
springProfiles.add("prod")
|
||||
} else {
|
||||
springProfiles.add("dev")
|
||||
}
|
||||
currentProfiles = springProfiles.join(",")
|
||||
logger.quiet("Current profiles are: " + currentProfiles)
|
||||
}
|
||||
|
||||
if (springProfiles.contains("front")) {
|
||||
apply from: "build.front.gradle"
|
||||
}
|
||||
if (springProfiles.contains("dev")) {
|
||||
apply from: "build.migrations.gradle"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
runtimeOnly "org.liquibase:liquibase-core:${liquibaseVersion}"
|
||||
|
||||
if (springProfiles.contains("prod")) {
|
||||
runtimeOnly "org.postgresql:postgresql:${postgresVersion}"
|
||||
} else {
|
||||
runtimeOnly "org.postgresql:postgresql:${postgresVersion}"
|
||||
runtimeOnly "com.h2database:h2:${h2Version}"
|
||||
}
|
||||
|
||||
implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:${springdocVersion}"
|
||||
|
||||
if (!springProfiles.contains("front")) {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation "nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:${thymeleafLayoutVersion}"
|
||||
developmentOnly 'org.springframework.boot:spring-boot-devtools'
|
||||
runtimeOnly "org.webjars.npm:bootstrap:${bootstrapVersion}"
|
||||
runtimeOnly "org.webjars.npm:bootstrap-icons:${bootstrapIconsVersion}"
|
||||
}
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
bootRun {
|
||||
def currentArgs = ["--spring.profiles.active=" + currentProfiles]
|
||||
if (project.hasProperty("args")) {
|
||||
currentArgs.addAll(project.args.split(","))
|
||||
}
|
||||
args currentArgs
|
||||
}
|
||||
|
||||
bootJar {
|
||||
archiveFileName = String.format("%s-%s.jar", rootProject.name, version)
|
||||
}
|
||||
|
||||
test {
|
||||
systemProperty "spring.profiles.active", currentProfiles
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
processResources {
|
||||
filesMatching("**/application.yml") {
|
||||
filter { line ->
|
||||
line.replace("active: dev", "active: ${currentProfiles}")
|
||||
}
|
||||
}
|
||||
}
|
||||
61
demo/build.migrations.gradle
Normal file
61
demo/build.migrations.gradle
Normal file
@@ -0,0 +1,61 @@
|
||||
apply plugin: "org.liquibase.gradle"
|
||||
|
||||
logger.quiet("Configure migrations generator")
|
||||
|
||||
ext {
|
||||
picocliVersion = "4.7.7"
|
||||
timestamp = new Date().format("yyyy-MM-dd-HHmmss")
|
||||
}
|
||||
|
||||
liquibase {
|
||||
activities {
|
||||
main {
|
||||
changelogFile "db/master.yml"
|
||||
url "jdbc:h2:file:./data"
|
||||
username "sa"
|
||||
password "sa"
|
||||
referenceUrl "hibernate:spring:com.example.demo.entity?dialect=org.hibernate.dialect.H2Dialect"
|
||||
logLevel "warn"
|
||||
}
|
||||
}
|
||||
}
|
||||
update.dependsOn processResources
|
||||
|
||||
dependencies {
|
||||
liquibaseRuntime "org.liquibase.ext:liquibase-hibernate6:${liquibaseVersion}"
|
||||
liquibaseRuntime "info.picocli:picocli:${picocliVersion}"
|
||||
liquibaseRuntime sourceSets.main.runtimeClasspath
|
||||
liquibaseRuntime sourceSets.main.output
|
||||
}
|
||||
|
||||
tasks.register("generateFull") {
|
||||
group = "migrations"
|
||||
description = "Generate changelog from existing database"
|
||||
doFirst(){
|
||||
liquibase {
|
||||
activities {
|
||||
main {
|
||||
changeLogFile "src/main/resources/db/generated-full-${timestamp}.yml"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finalizedBy generateChangelog
|
||||
}
|
||||
|
||||
tasks.register("generateDiff") {
|
||||
group = "liquibase"
|
||||
description = "Generate diff between DB and JPA entities"
|
||||
doFirst(){
|
||||
liquibase {
|
||||
activities {
|
||||
main {
|
||||
changeLogFile "src/main/resources/db/generated-diff-${timestamp}.yml"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finalizedBy diffChangelog
|
||||
}
|
||||
diffChangelog.dependsOn compileJava
|
||||
|
||||
BIN
demo/data.mv.db
Normal file
BIN
demo/data.mv.db
Normal file
Binary file not shown.
84
demo/data.trace.db
Normal file
84
demo/data.trace.db
Normal file
@@ -0,0 +1,84 @@
|
||||
2025-11-14 20:15:51.893939+04:00 jdbc[13]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "[*]DROPTABLE COUNTRIES"; ожидалось "DELETE, DROP"
|
||||
Syntax error in SQL statement "[*]DROPTABLE COUNTRIES"; expected "DELETE, DROP"; SQL statement:
|
||||
DROPTABLE COUNTRIES [42001-240]
|
||||
2025-11-14 20:16:02.103322+04:00 jdbc[13]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Невозможно удалить "COUNTRIES", пока существует зависимый объект "FK7SDOJ1330RH52SHDCVIL7SD4J"
|
||||
Cannot drop "COUNTRIES" because "FK7SDOJ1330RH52SHDCVIL7SD4J" depends on it; SQL statement:
|
||||
DROP TABLE COUNTRIES [90107-240]
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:644)
|
||||
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
|
||||
at org.h2.message.DbException.get(DbException.java:223)
|
||||
at org.h2.command.ddl.DropTable.prepareDrop(DropTable.java:104)
|
||||
at org.h2.command.ddl.DropTable.update(DropTable.java:129)
|
||||
at org.h2.command.CommandContainer.update(CommandContainer.java:139)
|
||||
at org.h2.command.Command.executeUpdate(Command.java:306)
|
||||
at org.h2.command.Command.executeUpdate(Command.java:250)
|
||||
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:262)
|
||||
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
|
||||
at org.h2.server.web.WebApp.getResult(WebApp.java:1344)
|
||||
at org.h2.server.web.WebApp.query(WebApp.java:1142)
|
||||
at org.h2.server.web.WebApp.query(WebApp.java:1118)
|
||||
at org.h2.server.web.WebApp.process(WebApp.java:244)
|
||||
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
|
||||
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
|
||||
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
|
||||
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:206)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
|
||||
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
|
||||
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
|
||||
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
|
||||
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
|
||||
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
|
||||
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
|
||||
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
|
||||
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
|
||||
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
|
||||
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
|
||||
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
|
||||
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
|
||||
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
|
||||
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
|
||||
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
|
||||
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
|
||||
at java.base/java.lang.Thread.run(Thread.java:1583)
|
||||
2025-11-14 22:31:12.810213+04:00 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "DATABASECHANGELOGLOCK" не найдена
|
||||
Table "DATABASECHANGELOGLOCK" not found; SQL statement:
|
||||
SELECT COUNT(*) FROM PUBLIC.DATABASECHANGELOGLOCK [42102-240]
|
||||
2025-11-14 22:31:12.937738+04:00 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "EPOCHS" уже существует
|
||||
Table "EPOCHS" already exists; SQL statement:
|
||||
CREATE TABLE PUBLIC.epochs (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, CONSTRAINT pk_epochs PRIMARY KEY (id)) [42101-240]
|
||||
2025-11-14 22:31:54.536358+04:00 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "EPOCHS" уже существует
|
||||
Table "EPOCHS" already exists; SQL statement:
|
||||
CREATE TABLE PUBLIC.epochs (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, CONSTRAINT pk_epochs PRIMARY KEY (id)) [42101-240]
|
||||
2025-11-14 23:14:44.601238+04:00 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "EPOCHS" уже существует
|
||||
Table "EPOCHS" already exists; SQL statement:
|
||||
CREATE TABLE PUBLIC.epochs (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, CONSTRAINT pk_epochs PRIMARY KEY (id)) [42101-240]
|
||||
2025-11-14 23:16:24.970110+04:00 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "EPOCHS" уже существует
|
||||
Table "EPOCHS" already exists; SQL statement:
|
||||
CREATE TABLE PUBLIC.epochs (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, CONSTRAINT pk_epochs PRIMARY KEY (id)) [42101-240]
|
||||
2025-11-14 23:17:25.045114+04:00 jdbc[3]: exception
|
||||
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "EPOCHS" уже существует
|
||||
Table "EPOCHS" already exists; SQL statement:
|
||||
CREATE TABLE PUBLIC.epochs (id BIGINT NOT NULL, name VARCHAR(255) NOT NULL, CONSTRAINT pk_epochs PRIMARY KEY (id)) [42101-240]
|
||||
BIN
demo/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
demo/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
demo/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
demo/gradle/wrapper/gradle-wrapper.properties
vendored
Normal 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
demo/gradlew
vendored
Normal file
251
demo/gradlew
vendored
Normal 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
demo/gradlew.bat
vendored
Normal file
94
demo/gradlew.bat
vendored
Normal 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
|
||||
6
demo/package-lock.json
generated
Normal file
6
demo/package-lock.json
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "demo",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
1
demo/settings.gradle
Normal file
1
demo/settings.gradle
Normal file
@@ -0,0 +1 @@
|
||||
rootProject.name = 'demo'
|
||||
13
demo/src/main/java/com/example/demo/DemoApplication.java
Normal file
13
demo/src/main/java/com/example/demo/DemoApplication.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
15
demo/src/main/java/com/example/demo/api/PageHelper.java
Normal file
15
demo/src/main/java/com/example/demo/api/PageHelper.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package com.example.demo.api;
|
||||
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
public class PageHelper {
|
||||
private PageHelper() {
|
||||
}
|
||||
|
||||
public static Pageable toPageable(int page, int size) {
|
||||
return PageRequest.of(page - 1, size, Sort.by("id"));
|
||||
}
|
||||
}
|
||||
|
||||
40
demo/src/main/java/com/example/demo/api/PageRs.java
Normal file
40
demo/src/main/java/com/example/demo/api/PageRs.java
Normal file
@@ -0,0 +1,40 @@
|
||||
package com.example.demo.api;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public record PageRs<D>(
|
||||
List<D> items,
|
||||
int itemsCount,
|
||||
int currentPage,
|
||||
int currentSize,
|
||||
int totalPages,
|
||||
long totalItems,
|
||||
boolean isFirst,
|
||||
boolean isLast,
|
||||
boolean hasNext,
|
||||
boolean hasPrevious) {
|
||||
|
||||
public List<D> items() {
|
||||
return Optional.ofNullable(items).orElse(Collections.emptyList());
|
||||
}
|
||||
|
||||
public static <D, E> PageRs<D> from(Page<E> page, Function<E, D> mapper) {
|
||||
return new PageRs<>(
|
||||
page.getContent().stream().map(mapper::apply).toList(),
|
||||
page.getNumberOfElements(),
|
||||
page.getNumber() + 1,
|
||||
page.getSize(),
|
||||
page.getTotalPages(),
|
||||
page.getTotalElements(),
|
||||
page.isFirst(),
|
||||
page.isLast(),
|
||||
page.hasNext(),
|
||||
page.hasPrevious());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.example.demo.config;
|
||||
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
@Configuration
|
||||
@Profile("front")
|
||||
public class OpenApiConfig {
|
||||
|
||||
@Bean
|
||||
public OpenAPI customOpenAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("Punk Rock API")
|
||||
.version("1.0.0")
|
||||
.description("REST API для управления данными о панк-рок исполнителях")
|
||||
.contact(new Contact()
|
||||
.name("Developer")
|
||||
.email("developer@example.com")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.demo.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String DEV_ORIGIN = "http://localhost:5173";
|
||||
public static final String API_URL = "/api";
|
||||
public static final String MVC_REDIRECT = "redirect:";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.example.demo.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Profile("!front")
|
||||
@Configuration
|
||||
public class MvcWebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addViewControllers(@NonNull ViewControllerRegistry registry) {
|
||||
registry.addRedirectViewController("/", "/page-artists");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(@NonNull ResourceHandlerRegistry registry) {
|
||||
registry
|
||||
.addResourceHandler("/webjars/**")
|
||||
.addResourceLocations("classpath:/META-INF/resources/webjars/");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.demo.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry
|
||||
.addMapping(Constants.API_URL + "/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedOrigins("http://localhost:3000", "http://localhost:5173", Constants.DEV_ORIGIN)
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
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.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import com.example.demo.api.PageHelper;
|
||||
import com.example.demo.api.PageRs;
|
||||
import com.example.demo.configuration.Constants;
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.service.ArtistService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + ArtistController.URL)
|
||||
public class ArtistController {
|
||||
public static final String URL = "/artists";
|
||||
private final ArtistService artistService;
|
||||
|
||||
public ArtistController(ArtistService artistService) {
|
||||
this.artistService = artistService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageRs<ArtistRs> getAll(
|
||||
@RequestParam(defaultValue = "1") @Min(1) int page,
|
||||
@RequestParam(defaultValue = "3") @Min(1) int size) {
|
||||
return artistService.getAll(PageHelper.toPageable(page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ArtistRs get(@PathVariable Long id) {
|
||||
return artistService.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ArtistRs create(@RequestBody @Valid ArtistRq dto) {
|
||||
return artistService.create(dto);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ArtistRs update(@PathVariable Long id, @RequestBody @Valid ArtistRq dto) {
|
||||
return artistService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ArtistRs delete(@PathVariable Long id) {
|
||||
return artistService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.configuration.Constants;
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.service.CountryService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + CountryController.URL)
|
||||
public class CountryController {
|
||||
public static final String URL = "/countries";
|
||||
private final CountryService countryService;
|
||||
|
||||
public CountryController(CountryService countryService) {
|
||||
this.countryService = countryService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CountryRs> getAll() {
|
||||
return countryService.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CountryRs get(@PathVariable Long id) {
|
||||
return countryService.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public CountryRs create(@RequestBody @Valid CountryRq dto) {
|
||||
return countryService.create(dto);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CountryRs update(@PathVariable Long id, @RequestBody @Valid CountryRq dto) {
|
||||
return countryService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CountryRs delete(@PathVariable Long id) {
|
||||
return countryService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.configuration.Constants;
|
||||
import com.example.demo.dto.EpochRq;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.service.EpochService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + EpochController.URL)
|
||||
public class EpochController {
|
||||
public static final String URL = "/epochs";
|
||||
private final EpochService epochService;
|
||||
|
||||
public EpochController(EpochService epochService) {
|
||||
this.epochService = epochService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<EpochRs> getAll() {
|
||||
return epochService.getAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public EpochRs get(@PathVariable Long id) {
|
||||
return epochService.get(id);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public EpochRs create(@RequestBody @Valid EpochRq dto) {
|
||||
return epochService.create(dto);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public EpochRs update(@PathVariable Long id, @RequestBody @Valid EpochRq dto) {
|
||||
return epochService.update(id, dto);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public EpochRs delete(@PathVariable Long id) {
|
||||
return epochService.delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@Profile("front")
|
||||
@Controller
|
||||
public class SpaController {
|
||||
@GetMapping(value = "/{path:^(?!api|assets|images|swagger-ui|.*\\.[a-zA-Z0-9]{2,10}).*}/**")
|
||||
public String forwardToIndex(@PathVariable(required = false) String path) {
|
||||
return "forward:/index.html";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.example.demo.controller.mvc;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.context.annotation.ScopedProxyMode;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@Component
|
||||
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||
public class ArtistFilterSession {
|
||||
private Long countryId;
|
||||
private Long epochId;
|
||||
|
||||
public Long getCountryId() {
|
||||
return countryId;
|
||||
}
|
||||
|
||||
public void setCountryId(Long countryId) {
|
||||
this.countryId = countryId;
|
||||
}
|
||||
|
||||
public Long getEpochId() {
|
||||
return epochId;
|
||||
}
|
||||
|
||||
public void setEpochId(Long epochId) {
|
||||
this.epochId = epochId;
|
||||
}
|
||||
|
||||
public void clearFilters() {
|
||||
this.countryId = null;
|
||||
this.epochId = null;
|
||||
}
|
||||
|
||||
public boolean hasFilters() {
|
||||
return countryId != null || epochId != null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
package com.example.demo.controller.mvc;
|
||||
|
||||
import static com.example.demo.configuration.Constants.MVC_REDIRECT;
|
||||
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.SessionAttributes;
|
||||
import org.springframework.web.bind.support.SessionStatus;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.api.PageHelper;
|
||||
import com.example.demo.api.PageRs;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.dto.mvc.ArtistFormDto;
|
||||
import com.example.demo.service.ArtistService;
|
||||
import com.example.demo.service.CountryService;
|
||||
import com.example.demo.service.EpochService;
|
||||
|
||||
@Profile("!front")
|
||||
@SessionAttributes(ArtistMvcController.ATR_COUNTRIES)
|
||||
@Controller
|
||||
@RequestMapping("/" + ArtistMvcController.VIEW)
|
||||
public class ArtistMvcController {
|
||||
public static final String VIEW = "page-artists";
|
||||
private static final String VIEW_EDIT = "page-artists-edit";
|
||||
|
||||
private static final String ATR_ARTIST = "artist";
|
||||
public static final String ATR_COUNTRIES = "countries";
|
||||
public static final String ATR_EPOCHS = "epochs";
|
||||
private static final String ATR_PAGE = "page";
|
||||
private static final String ATR_ARTISTS = "artists";
|
||||
|
||||
private final ArtistService artistService;
|
||||
private final CountryService countryService;
|
||||
private final EpochService epochService;
|
||||
private final ArtistFilterSession filterSession;
|
||||
|
||||
public ArtistMvcController(
|
||||
ArtistService artistService,
|
||||
CountryService countryService,
|
||||
EpochService epochService,
|
||||
ArtistFilterSession filterSession) {
|
||||
this.artistService = artistService;
|
||||
this.countryService = countryService;
|
||||
this.epochService = epochService;
|
||||
this.filterSession = filterSession;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@RequestParam(defaultValue = "3") int size,
|
||||
@RequestParam(required = false) Long countryId,
|
||||
@RequestParam(required = false) Long epochId,
|
||||
SessionStatus sessionStatus,
|
||||
Model model) {
|
||||
if (countryId != null) {
|
||||
filterSession.setCountryId(countryId);
|
||||
}
|
||||
if (epochId != null) {
|
||||
filterSession.setEpochId(epochId);
|
||||
}
|
||||
|
||||
final PageRs<ArtistRs> artists = artistService.getAllFiltered(
|
||||
filterSession.getCountryId(),
|
||||
filterSession.getEpochId(),
|
||||
PageHelper.toPageable(page, size));
|
||||
|
||||
if (artists.itemsCount() == 0 && page > 1) {
|
||||
return MVC_REDIRECT + "/" + VIEW;
|
||||
}
|
||||
|
||||
model.addAttribute(ATR_ARTISTS, artists);
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
model.addAttribute(ATR_COUNTRIES, countryService.getAll());
|
||||
model.addAttribute(ATR_EPOCHS, epochService.getAll());
|
||||
model.addAttribute("selectedCountryId", filterSession.getCountryId());
|
||||
model.addAttribute("selectedEpochId", filterSession.getEpochId());
|
||||
sessionStatus.setComplete();
|
||||
return VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/filter")
|
||||
public String applyFilter(
|
||||
@RequestParam(required = false) Long countryId,
|
||||
@RequestParam(required = false) Long epochId,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
filterSession.setCountryId(countryId);
|
||||
filterSession.setEpochId(epochId);
|
||||
redirectAttributes.addAttribute(ATR_PAGE, 1);
|
||||
return MVC_REDIRECT + "/" + VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/filter/clear")
|
||||
public String clearFilter(RedirectAttributes redirectAttributes) {
|
||||
filterSession.clearFilters();
|
||||
redirectAttributes.addAttribute(ATR_PAGE, 1);
|
||||
return MVC_REDIRECT + "/" + VIEW;
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/edit", "/edit/" })
|
||||
public String create(@RequestParam(defaultValue = "1") int page, Model model) {
|
||||
final ArtistFormDto artist = ArtistFormDto.empty();
|
||||
model.addAttribute(ATR_ARTIST, artist);
|
||||
model.addAttribute(ATR_COUNTRIES, countryService.getAll());
|
||||
model.addAttribute(ATR_EPOCHS, epochService.getAll());
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
|
||||
@PostMapping(value = { "/edit", "/edit/" })
|
||||
public String create(
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@ModelAttribute(name = ATR_ARTIST) @Valid ArtistFormDto dto,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(ATR_COUNTRIES, countryService.getAll());
|
||||
model.addAttribute(ATR_EPOCHS, epochService.getAll());
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
final ArtistRs artist = artistService.create(dto.toRq());
|
||||
redirectAttributes.addAttribute(ATR_PAGE, page);
|
||||
redirectAttributes.addFlashAttribute("successSave", true);
|
||||
return MVC_REDIRECT + "/" + VIEW + "/edit/" + artist.getId();
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(@PathVariable Long id, @RequestParam(defaultValue = "1") int page, Model model) {
|
||||
final ArtistFormDto artist = ArtistFormDto.fromRs(artistService.get(id));
|
||||
model.addAttribute(ATR_ARTIST, artist);
|
||||
model.addAttribute(ATR_COUNTRIES, countryService.getAll());
|
||||
model.addAttribute(ATR_EPOCHS, epochService.getAll());
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable Long id,
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@ModelAttribute(name = ATR_ARTIST) @Valid ArtistFormDto dto,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(ATR_COUNTRIES, countryService.getAll());
|
||||
model.addAttribute(ATR_EPOCHS, epochService.getAll());
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
final ArtistRs artist = artistService.update(id, dto.toRq());
|
||||
redirectAttributes.addAttribute(ATR_PAGE, page);
|
||||
redirectAttributes.addFlashAttribute("successSave", true);
|
||||
return MVC_REDIRECT + "/" + VIEW + "/edit/" + artist.getId();
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable Long id,
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
artistService.delete(id);
|
||||
redirectAttributes.addAttribute(ATR_PAGE, page);
|
||||
return MVC_REDIRECT + "/" + VIEW;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.example.demo.controller.mvc;
|
||||
|
||||
import static com.example.demo.configuration.Constants.MVC_REDIRECT;
|
||||
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.SessionAttributes;
|
||||
import org.springframework.web.bind.support.SessionStatus;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import com.example.demo.api.PageHelper;
|
||||
import com.example.demo.api.PageRs;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.dto.mvc.CountryFormDto;
|
||||
import com.example.demo.service.CountryService;
|
||||
|
||||
@Profile("!front")
|
||||
@SessionAttributes(CountryMvcController.ATR_COUNTRIES)
|
||||
@Controller
|
||||
@RequestMapping("/" + CountryMvcController.VIEW)
|
||||
public class CountryMvcController {
|
||||
public static final String VIEW = "page-countries";
|
||||
private static final String VIEW_EDIT = "page-countries-edit";
|
||||
|
||||
private static final String ATR_COUNTRY = "country";
|
||||
public static final String ATR_COUNTRIES = "countries";
|
||||
private static final String ATR_PAGE = "page";
|
||||
|
||||
private final CountryService countryService;
|
||||
|
||||
public CountryMvcController(CountryService countryService) {
|
||||
this.countryService = countryService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@RequestParam(defaultValue = "3") int size,
|
||||
SessionStatus sessionStatus,
|
||||
Model model) {
|
||||
final PageRs<CountryRs> countries = countryService.getAll(PageHelper.toPageable(page, size));
|
||||
if (countries.itemsCount() == 0 && page > 1) {
|
||||
return MVC_REDIRECT + "/" + VIEW;
|
||||
}
|
||||
model.addAttribute(ATR_COUNTRIES, countries);
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
sessionStatus.setComplete();
|
||||
return VIEW;
|
||||
}
|
||||
|
||||
@GetMapping(value = { "/edit", "/edit/" })
|
||||
public String create(@RequestParam(defaultValue = "1") int page, Model model) {
|
||||
final CountryFormDto country = CountryFormDto.empty();
|
||||
model.addAttribute(ATR_COUNTRY, country);
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
|
||||
@PostMapping(value = { "/edit", "/edit/" })
|
||||
public String create(
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@ModelAttribute(name = ATR_COUNTRY) @Valid CountryFormDto dto,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
final CountryRs country = countryService.create(dto.toRq());
|
||||
redirectAttributes.addAttribute(ATR_PAGE, page);
|
||||
redirectAttributes.addFlashAttribute("successSave", true);
|
||||
return MVC_REDIRECT + "/" + VIEW + "/edit/" + country.getId();
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(@PathVariable Long id, @RequestParam(defaultValue = "1") int page, Model model) {
|
||||
final CountryFormDto country = CountryFormDto.fromRs(countryService.get(id));
|
||||
model.addAttribute(ATR_COUNTRY, country);
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable Long id,
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
@ModelAttribute(name = ATR_COUNTRY) @Valid CountryFormDto dto,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(ATR_PAGE, page);
|
||||
return VIEW_EDIT;
|
||||
}
|
||||
final CountryRs country = countryService.update(id, dto.toRq());
|
||||
redirectAttributes.addAttribute(ATR_PAGE, page);
|
||||
redirectAttributes.addFlashAttribute("successSave", true);
|
||||
return MVC_REDIRECT + "/" + VIEW + "/edit/" + country.getId();
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable Long id,
|
||||
@RequestParam(defaultValue = "1") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
countryService.delete(id);
|
||||
redirectAttributes.addAttribute(ATR_PAGE, page);
|
||||
return MVC_REDIRECT + "/" + VIEW;
|
||||
}
|
||||
}
|
||||
|
||||
59
demo/src/main/java/com/example/demo/dto/ArtistDto.java
Normal file
59
demo/src/main/java/com/example/demo/dto/ArtistDto.java
Normal file
@@ -0,0 +1,59 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class ArtistDto {
|
||||
private Integer id;
|
||||
private String name;
|
||||
private String description;
|
||||
private Integer epochId;
|
||||
private Integer countryId;
|
||||
|
||||
public ArtistDto() {}
|
||||
|
||||
public ArtistDto(Integer id, String name, String description, Integer epochId, Integer countryId) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.epochId = epochId;
|
||||
this.countryId = countryId;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getEpochId() {
|
||||
return epochId;
|
||||
}
|
||||
|
||||
public void setEpochId(Integer epochId) {
|
||||
this.epochId = epochId;
|
||||
}
|
||||
|
||||
public Integer getCountryId() {
|
||||
return countryId;
|
||||
}
|
||||
|
||||
public void setCountryId(Integer countryId) {
|
||||
this.countryId = countryId;
|
||||
}
|
||||
}
|
||||
47
demo/src/main/java/com/example/demo/dto/ArtistRq.java
Normal file
47
demo/src/main/java/com/example/demo/dto/ArtistRq.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class ArtistRq {
|
||||
@NotBlank
|
||||
private String name;
|
||||
private String description;
|
||||
@NotNull
|
||||
private Long epochId;
|
||||
@NotNull
|
||||
private Long countryId;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Long getEpochId() {
|
||||
return epochId;
|
||||
}
|
||||
|
||||
public void setEpochId(Long epochId) {
|
||||
this.epochId = epochId;
|
||||
}
|
||||
|
||||
public Long getCountryId() {
|
||||
return countryId;
|
||||
}
|
||||
|
||||
public void setCountryId(Long countryId) {
|
||||
this.countryId = countryId;
|
||||
}
|
||||
}
|
||||
|
||||
50
demo/src/main/java/com/example/demo/dto/ArtistRs.java
Normal file
50
demo/src/main/java/com/example/demo/dto/ArtistRs.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class ArtistRs {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private EpochRs epoch;
|
||||
private CountryRs country;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public EpochRs getEpoch() {
|
||||
return epoch;
|
||||
}
|
||||
|
||||
public void setEpoch(EpochRs epoch) {
|
||||
this.epoch = epoch;
|
||||
}
|
||||
|
||||
public CountryRs getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(CountryRs country) {
|
||||
this.country = country;
|
||||
}
|
||||
}
|
||||
|
||||
29
demo/src/main/java/com/example/demo/dto/CountryDto.java
Normal file
29
demo/src/main/java/com/example/demo/dto/CountryDto.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class CountryDto {
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public CountryDto() {}
|
||||
|
||||
public CountryDto(Integer id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
17
demo/src/main/java/com/example/demo/dto/CountryRq.java
Normal file
17
demo/src/main/java/com/example/demo/dto/CountryRq.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class CountryRq {
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
23
demo/src/main/java/com/example/demo/dto/CountryRs.java
Normal file
23
demo/src/main/java/com/example/demo/dto/CountryRs.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class CountryRs {
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
29
demo/src/main/java/com/example/demo/dto/EpochDto.java
Normal file
29
demo/src/main/java/com/example/demo/dto/EpochDto.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class EpochDto {
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public EpochDto() {}
|
||||
|
||||
public EpochDto(Integer id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
17
demo/src/main/java/com/example/demo/dto/EpochRq.java
Normal file
17
demo/src/main/java/com/example/demo/dto/EpochRq.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class EpochRq {
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
23
demo/src/main/java/com/example/demo/dto/EpochRs.java
Normal file
23
demo/src/main/java/com/example/demo/dto/EpochRs.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class EpochRs {
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.example.demo.dto.mvc;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
|
||||
public record ArtistFormDto(
|
||||
Long id,
|
||||
@NotBlank String name,
|
||||
String description,
|
||||
@NotNull @Min(1) Long epochId,
|
||||
@NotNull @Min(1) Long countryId) {
|
||||
|
||||
public static ArtistFormDto empty() {
|
||||
return new ArtistFormDto(null, null, null, -1L, -1L);
|
||||
}
|
||||
|
||||
public static ArtistFormDto fromRs(ArtistRs item) {
|
||||
return new ArtistFormDto(
|
||||
item.getId(),
|
||||
item.getName(),
|
||||
item.getDescription(),
|
||||
Optional.ofNullable(item.getEpoch()).map(EpochRs::getId).orElse(-1L),
|
||||
Optional.ofNullable(item.getCountry()).map(CountryRs::getId).orElse(-1L));
|
||||
}
|
||||
|
||||
public ArtistRq toRq() {
|
||||
ArtistRq rq = new ArtistRq();
|
||||
rq.setName(name);
|
||||
rq.setDescription(description);
|
||||
rq.setEpochId(epochId);
|
||||
rq.setCountryId(countryId);
|
||||
return rq;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.example.demo.dto.mvc;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
|
||||
public record CountryFormDto(
|
||||
Long id,
|
||||
@NotBlank String name) {
|
||||
|
||||
public static CountryFormDto empty() {
|
||||
return new CountryFormDto(null, null);
|
||||
}
|
||||
|
||||
public static CountryFormDto fromRs(CountryRs item) {
|
||||
return new CountryFormDto(item.getId(), item.getName());
|
||||
}
|
||||
|
||||
public CountryRq toRq() {
|
||||
CountryRq rq = new CountryRq();
|
||||
rq.setName(name);
|
||||
return rq;
|
||||
}
|
||||
}
|
||||
|
||||
92
demo/src/main/java/com/example/demo/entity/ArtistEntity.java
Normal file
92
demo/src/main/java/com/example/demo/entity/ArtistEntity.java
Normal file
@@ -0,0 +1,92 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "artists")
|
||||
public class ArtistEntity extends BaseEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(columnDefinition = "text")
|
||||
private String description;
|
||||
|
||||
@JoinColumn(name = "epoch_id", nullable = false)
|
||||
@ManyToOne
|
||||
private EpochEntity epoch;
|
||||
|
||||
@JoinColumn(name = "country_id", nullable = false)
|
||||
@ManyToOne
|
||||
private CountryEntity country;
|
||||
|
||||
public ArtistEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ArtistEntity(String name, String description, EpochEntity epoch, CountryEntity country) {
|
||||
this();
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
setEpoch(epoch);
|
||||
setCountry(country);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public EpochEntity getEpoch() {
|
||||
return epoch;
|
||||
}
|
||||
|
||||
public void setEpoch(EpochEntity epoch) {
|
||||
if (this.epoch == epoch) {
|
||||
return;
|
||||
}
|
||||
if (this.epoch != null) {
|
||||
EpochEntity oldEpoch = this.epoch;
|
||||
this.epoch = null;
|
||||
oldEpoch.removeArtist(this);
|
||||
}
|
||||
this.epoch = epoch;
|
||||
if (epoch != null) {
|
||||
epoch.addArtist(this);
|
||||
}
|
||||
}
|
||||
|
||||
public CountryEntity getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(CountryEntity country) {
|
||||
if (this.country == country) {
|
||||
return;
|
||||
}
|
||||
if (this.country != null) {
|
||||
CountryEntity oldCountry = this.country;
|
||||
this.country = null;
|
||||
oldCountry.removeArtist(this);
|
||||
}
|
||||
this.country = country;
|
||||
if (country != null) {
|
||||
country.addArtist(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
27
demo/src/main/java/com/example/demo/entity/BaseEntity.java
Normal file
27
demo/src/main/java/com/example/demo/entity/BaseEntity.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
@SequenceGenerator(name = "hibernate_sequence")
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "countries")
|
||||
public class CountryEntity extends BaseEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "country")
|
||||
@OrderBy("id ASC")
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
|
||||
public CountryEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CountryEntity(String name) {
|
||||
this();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<ArtistEntity> getArtists() {
|
||||
return artists;
|
||||
}
|
||||
|
||||
public void addArtist(ArtistEntity artist) {
|
||||
if (!artists.contains(artist)) {
|
||||
artists.add(artist);
|
||||
if (artist.getCountry() != this) {
|
||||
artist.setCountry(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeArtist(ArtistEntity artist) {
|
||||
if (artists.contains(artist)) {
|
||||
artists.remove(artist);
|
||||
if (artist.getCountry() == this) {
|
||||
artist.setCountry(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
61
demo/src/main/java/com/example/demo/entity/EpochEntity.java
Normal file
61
demo/src/main/java/com/example/demo/entity/EpochEntity.java
Normal file
@@ -0,0 +1,61 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "epochs")
|
||||
public class EpochEntity extends BaseEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "epoch")
|
||||
@OrderBy("id ASC")
|
||||
private Set<ArtistEntity> artists = new HashSet<>();
|
||||
|
||||
public EpochEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EpochEntity(String name) {
|
||||
this();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<ArtistEntity> getArtists() {
|
||||
return artists;
|
||||
}
|
||||
|
||||
public void addArtist(ArtistEntity artist) {
|
||||
if (!artists.contains(artist)) {
|
||||
artists.add(artist);
|
||||
if (artist.getEpoch() != this) {
|
||||
artist.setEpoch(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void removeArtist(ArtistEntity artist) {
|
||||
if (artists.contains(artist)) {
|
||||
artists.remove(artist);
|
||||
if (artist.getEpoch() == this) {
|
||||
artist.setEpoch(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.demo.entity.projection;
|
||||
|
||||
public interface ArtistStatsProjection {
|
||||
Long getTotalArtists();
|
||||
Long getArtistsWithDescription();
|
||||
Long getArtistsWithoutDescription();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.example.demo.entity.projection;
|
||||
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
|
||||
public interface CountryStatsProjection {
|
||||
CountryEntity getCountry();
|
||||
Long getArtistsCount();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.example.demo.entity.projection;
|
||||
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
|
||||
public interface EpochStatsProjection {
|
||||
EpochEntity getEpoch();
|
||||
Long getArtistsCount();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.example.demo.error;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public <T> NotFoundException(Class<T> entClass, Long id) {
|
||||
super(String.format("%s with id %s is not found", entClass.getSimpleName(), id));
|
||||
}
|
||||
}
|
||||
|
||||
51
demo/src/main/java/com/example/demo/mapper/ArtistMapper.java
Normal file
51
demo/src/main/java/com/example/demo/mapper/ArtistMapper.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.example.demo.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.entity.ArtistEntity;
|
||||
|
||||
@Component
|
||||
public class ArtistMapper {
|
||||
private final EpochMapper epochMapper;
|
||||
private final CountryMapper countryMapper;
|
||||
|
||||
public ArtistMapper(EpochMapper epochMapper, CountryMapper countryMapper) {
|
||||
this.epochMapper = epochMapper;
|
||||
this.countryMapper = countryMapper;
|
||||
}
|
||||
|
||||
public ArtistRq toRqDto(String name, String description, Long epochId, Long countryId) {
|
||||
final ArtistRq dto = new ArtistRq();
|
||||
dto.setName(name);
|
||||
dto.setDescription(description);
|
||||
dto.setEpochId(epochId);
|
||||
dto.setCountryId(countryId);
|
||||
return dto;
|
||||
}
|
||||
|
||||
public ArtistRs toRsDto(ArtistEntity entity) {
|
||||
final ArtistRs dto = new ArtistRs();
|
||||
dto.setId(entity.getId());
|
||||
dto.setName(entity.getName());
|
||||
dto.setDescription(entity.getDescription());
|
||||
if (entity.getEpoch() != null) {
|
||||
dto.setEpoch(epochMapper.toRsDto(entity.getEpoch()));
|
||||
}
|
||||
if (entity.getCountry() != null) {
|
||||
dto.setCountry(countryMapper.toRsDto(entity.getCountry()));
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<ArtistRs> toRsDtoList(Iterable<ArtistEntity> entities) {
|
||||
return StreamSupport.stream(entities.spliterator(), false)
|
||||
.map(this::toRsDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.example.demo.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
|
||||
@Component
|
||||
public class CountryMapper {
|
||||
public CountryRq toRqDto(String name) {
|
||||
final CountryRq dto = new CountryRq();
|
||||
dto.setName(name);
|
||||
return dto;
|
||||
}
|
||||
|
||||
public CountryRs toRsDto(CountryEntity entity) {
|
||||
final CountryRs dto = new CountryRs();
|
||||
dto.setId(entity.getId());
|
||||
dto.setName(entity.getName());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<CountryRs> toRsDtoList(Iterable<CountryEntity> entities) {
|
||||
return StreamSupport.stream(entities.spliterator(), false)
|
||||
.map(this::toRsDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
33
demo/src/main/java/com/example/demo/mapper/EpochMapper.java
Normal file
33
demo/src/main/java/com/example/demo/mapper/EpochMapper.java
Normal file
@@ -0,0 +1,33 @@
|
||||
package com.example.demo.mapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.example.demo.dto.EpochRq;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
|
||||
@Component
|
||||
public class EpochMapper {
|
||||
public EpochRq toRqDto(String name) {
|
||||
final EpochRq dto = new EpochRq();
|
||||
dto.setName(name);
|
||||
return dto;
|
||||
}
|
||||
|
||||
public EpochRs toRsDto(EpochEntity entity) {
|
||||
final EpochRs dto = new EpochRs();
|
||||
dto.setId(entity.getId());
|
||||
dto.setName(entity.getName());
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<EpochRs> toRsDtoList(Iterable<EpochEntity> entities) {
|
||||
return StreamSupport.stream(entities.spliterator(), false)
|
||||
.map(this::toRsDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.entity.ArtistEntity;
|
||||
import com.example.demo.entity.projection.ArtistStatsProjection;
|
||||
|
||||
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long> {
|
||||
List<ArtistEntity> findByEpochId(Long epochId);
|
||||
|
||||
List<ArtistEntity> findByCountryId(Long countryId);
|
||||
|
||||
List<ArtistEntity> findByEpochIdAndCountryId(Long epochId, Long countryId);
|
||||
|
||||
Page<ArtistEntity> findByEpochId(Long epochId, Pageable pageable);
|
||||
|
||||
Page<ArtistEntity> findByCountryId(Long countryId, Pageable pageable);
|
||||
|
||||
Page<ArtistEntity> findByEpochIdAndCountryId(Long epochId, Long countryId, Pageable pageable);
|
||||
|
||||
@Query("select count(a) as totalArtists, " +
|
||||
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
|
||||
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
|
||||
"from ArtistEntity a")
|
||||
ArtistStatsProjection getArtistsStatistics();
|
||||
|
||||
@Query("select count(a) as totalArtists, " +
|
||||
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
|
||||
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
|
||||
"from ArtistEntity a " +
|
||||
"where a.epoch.id = :epochId")
|
||||
ArtistStatsProjection getArtistsStatisticsByEpoch(@Param("epochId") Long epochId);
|
||||
|
||||
@Query("select count(a) as totalArtists, " +
|
||||
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
|
||||
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
|
||||
"from ArtistEntity a " +
|
||||
"where a.country.id = :countryId")
|
||||
ArtistStatsProjection getArtistsStatisticsByCountry(@Param("countryId") Long countryId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
import com.example.demo.entity.projection.CountryStatsProjection;
|
||||
|
||||
public interface CountryRepository extends JpaRepository<CountryEntity, Long> {
|
||||
Optional<CountryEntity> findOneByNameIgnoreCase(String name);
|
||||
|
||||
@Query("select c as country, count(a) as artistsCount " +
|
||||
"from CountryEntity c left join c.artists a " +
|
||||
"group by c " +
|
||||
"order by c.id")
|
||||
List<CountryStatsProjection> getAllCountriesStatistics();
|
||||
|
||||
@Query("select c as country, count(a) as artistsCount " +
|
||||
"from CountryEntity c left join c.artists a " +
|
||||
"where c.id = :countryId " +
|
||||
"group by c")
|
||||
CountryStatsProjection getCountryStatistics(@Param("countryId") Long countryId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
import com.example.demo.entity.projection.EpochStatsProjection;
|
||||
|
||||
public interface EpochRepository extends JpaRepository<EpochEntity, Long> {
|
||||
Optional<EpochEntity> findOneByNameIgnoreCase(String name);
|
||||
|
||||
@Query("select e as epoch, count(a) as artistsCount " +
|
||||
"from EpochEntity e left join e.artists a " +
|
||||
"group by e " +
|
||||
"order by e.id")
|
||||
List<EpochStatsProjection> getAllEpochsStatistics();
|
||||
|
||||
@Query("select e as epoch, count(a) as artistsCount " +
|
||||
"from EpochEntity e left join e.artists a " +
|
||||
"where e.id = :epochId " +
|
||||
"group by e")
|
||||
EpochStatsProjection getEpochStatistics(@Param("epochId") Long epochId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.api.PageRs;
|
||||
import com.example.demo.dto.ArtistRq;
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.entity.ArtistEntity;
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.ArtistMapper;
|
||||
import com.example.demo.repository.ArtistRepository;
|
||||
|
||||
@Service
|
||||
public class ArtistService {
|
||||
private final ArtistRepository repository;
|
||||
private final EpochService epochService;
|
||||
private final CountryService countryService;
|
||||
private final ArtistMapper mapper;
|
||||
|
||||
public ArtistService(ArtistRepository repository, EpochService epochService,
|
||||
CountryService countryService, ArtistMapper mapper) {
|
||||
this.repository = repository;
|
||||
this.epochService = epochService;
|
||||
this.countryService = countryService;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public ArtistEntity getEntity(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(ArtistEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public PageRs<ArtistRs> getAll(Pageable pageable) {
|
||||
return PageRs.from(repository.findAll(pageable), mapper::toRsDto);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public PageRs<ArtistRs> getAllFiltered(Long countryId, Long epochId, Pageable pageable) {
|
||||
Page<ArtistEntity> page;
|
||||
if (countryId != null && epochId != null) {
|
||||
page = repository.findByEpochIdAndCountryId(epochId, countryId, pageable);
|
||||
} else if (countryId != null) {
|
||||
page = repository.findByCountryId(countryId, pageable);
|
||||
} else if (epochId != null) {
|
||||
page = repository.findByEpochId(epochId, pageable);
|
||||
} else {
|
||||
page = repository.findAll(pageable);
|
||||
}
|
||||
return PageRs.from(page, mapper::toRsDto);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ArtistRs get(Long id) {
|
||||
final ArtistEntity entity = getEntity(id);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ArtistRs create(ArtistRq dto) {
|
||||
final EpochEntity epoch = epochService.getEntity(dto.getEpochId());
|
||||
final CountryEntity country = countryService.getEntity(dto.getCountryId());
|
||||
ArtistEntity entity = new ArtistEntity(
|
||||
dto.getName(),
|
||||
dto.getDescription(),
|
||||
epoch,
|
||||
country);
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ArtistRs update(Long id, ArtistRq dto) {
|
||||
ArtistEntity entity = getEntity(id);
|
||||
entity.setName(dto.getName());
|
||||
entity.setDescription(dto.getDescription());
|
||||
entity.setEpoch(epochService.getEntity(dto.getEpochId()));
|
||||
entity.setCountry(countryService.getEntity(dto.getCountryId()));
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ArtistRs delete(Long id) {
|
||||
final ArtistEntity entity = getEntity(id);
|
||||
repository.delete(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.api.PageRs;
|
||||
import com.example.demo.dto.CountryRq;
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.entity.CountryEntity;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.CountryMapper;
|
||||
import com.example.demo.repository.CountryRepository;
|
||||
|
||||
@Service
|
||||
public class CountryService {
|
||||
private final CountryRepository repository;
|
||||
private final CountryMapper mapper;
|
||||
|
||||
public CountryService(CountryRepository repository, CountryMapper mapper) {
|
||||
this.repository = repository;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public CountryEntity getEntity(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(CountryEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CountryRs> getAll() {
|
||||
return mapper.toRsDtoList(repository.findAll());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public PageRs<CountryRs> getAll(Pageable pageable) {
|
||||
return PageRs.from(repository.findAll(pageable), mapper::toRsDto);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public CountryRs get(Long id) {
|
||||
final CountryEntity entity = getEntity(id);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CountryRs create(CountryRq dto) {
|
||||
CountryEntity entity = new CountryEntity(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CountryRs update(Long id, CountryRq dto) {
|
||||
CountryEntity entity = getEntity(id);
|
||||
entity.setName(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CountryRs delete(Long id) {
|
||||
final CountryEntity entity = getEntity(id);
|
||||
repository.delete(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.dto.EpochRq;
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.entity.EpochEntity;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.EpochMapper;
|
||||
import com.example.demo.repository.EpochRepository;
|
||||
|
||||
@Service
|
||||
public class EpochService {
|
||||
private final EpochRepository repository;
|
||||
private final EpochMapper mapper;
|
||||
|
||||
public EpochService(EpochRepository repository, EpochMapper mapper) {
|
||||
this.repository = repository;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public EpochEntity getEntity(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(EpochEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<EpochRs> getAll() {
|
||||
return mapper.toRsDtoList(repository.findAll());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public EpochRs get(Long id) {
|
||||
final EpochEntity entity = getEntity(id);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EpochRs create(EpochRq dto) {
|
||||
EpochEntity entity = new EpochEntity(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EpochRs update(Long id, EpochRq dto) {
|
||||
EpochEntity entity = getEntity(id);
|
||||
entity.setName(dto.getName());
|
||||
entity = repository.save(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EpochRs delete(Long id) {
|
||||
final EpochEntity entity = getEntity(id);
|
||||
repository.delete(entity);
|
||||
return mapper.toRsDto(entity);
|
||||
}
|
||||
}
|
||||
|
||||
21
demo/src/main/resources/application-dev.yml
Normal file
21
demo/src/main/resources/application-dev.yml
Normal file
@@ -0,0 +1,21 @@
|
||||
# Available levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging:
|
||||
level:
|
||||
com:
|
||||
example:
|
||||
demo: DEBUG
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:h2:file:./data
|
||||
username: sa
|
||||
password: sa
|
||||
driver-class-name: org.h2.Driver
|
||||
h2:
|
||||
console:
|
||||
enabled: true
|
||||
jpa:
|
||||
show-sql: false
|
||||
properties:
|
||||
hibernate:
|
||||
format-sql: false
|
||||
|
||||
20
demo/src/main/resources/application-prod.yml
Normal file
20
demo/src/main/resources/application-prod.yml
Normal file
@@ -0,0 +1,20 @@
|
||||
# Available levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging:
|
||||
level:
|
||||
com:
|
||||
example:
|
||||
demo: INFO
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:postgresql://127.0.0.1/demo
|
||||
username: postgres
|
||||
password: postgres
|
||||
driver-class-name: org.postgresql.Driver
|
||||
jpa:
|
||||
show-sql: false
|
||||
properties:
|
||||
hibernate:
|
||||
jdbc:
|
||||
lob:
|
||||
non_contextual_creation: true
|
||||
|
||||
12
demo/src/main/resources/application.properties
Normal file
12
demo/src/main/resources/application.properties
Normal file
@@ -0,0 +1,12 @@
|
||||
spring.application.name=demo
|
||||
server.port=8080
|
||||
springdoc.api-docs.path=/api-docs
|
||||
springdoc.swagger-ui.path=/swagger-ui.html
|
||||
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.h2.console.enabled=true
|
||||
29
demo/src/main/resources/application.yml
Normal file
29
demo/src/main/resources/application.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
spring:
|
||||
main:
|
||||
banner-mode: off
|
||||
application:
|
||||
name: demo
|
||||
profiles:
|
||||
active: dev
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
open-in-view: false
|
||||
properties:
|
||||
hibernate:
|
||||
jdbc:
|
||||
lob:
|
||||
non_contextual_creation: true
|
||||
liquibase:
|
||||
enabled: true
|
||||
drop-first: false
|
||||
change-log: classpath:db/master.yml
|
||||
server:
|
||||
port: 8080
|
||||
springdoc:
|
||||
api-docs:
|
||||
path: /api-docs
|
||||
swagger-ui:
|
||||
path: /swagger-ui.html
|
||||
|
||||
|
||||
18
demo/src/main/resources/db/changes/0-sequences.yml
Normal file
18
demo/src/main/resources/db/changes/0-sequences.yml
Normal file
@@ -0,0 +1,18 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: create-sequences
|
||||
author: user
|
||||
preConditions:
|
||||
- onFail: MARK_RAN
|
||||
- not:
|
||||
- sequenceExists:
|
||||
sequenceName: hibernate_sequence
|
||||
changes:
|
||||
- createSequence:
|
||||
sequenceName: hibernate_sequence
|
||||
startValue: 1
|
||||
incrementBy: 50
|
||||
minValue: 1
|
||||
cycle: false
|
||||
dataType: bigint
|
||||
|
||||
73
demo/src/main/resources/db/changes/1-tables.yml
Normal file
73
demo/src/main/resources/db/changes/1-tables.yml
Normal file
@@ -0,0 +1,73 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: create-tables
|
||||
author: user
|
||||
preConditions:
|
||||
- onFail: MARK_RAN
|
||||
- not:
|
||||
- tableExists:
|
||||
tableName: epochs
|
||||
changes:
|
||||
- createTable:
|
||||
tableName: epochs
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: BIGINT
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
primaryKeyName: pk_epochs
|
||||
- column:
|
||||
name: name
|
||||
type: VARCHAR(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- createTable:
|
||||
tableName: countries
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: BIGINT
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
primaryKeyName: pk_countries
|
||||
- column:
|
||||
name: name
|
||||
type: VARCHAR(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- createTable:
|
||||
tableName: artists
|
||||
columns:
|
||||
- column:
|
||||
name: id
|
||||
type: BIGINT
|
||||
constraints:
|
||||
primaryKey: true
|
||||
nullable: false
|
||||
primaryKeyName: pk_artists
|
||||
- column:
|
||||
name: name
|
||||
type: VARCHAR(255)
|
||||
constraints:
|
||||
nullable: false
|
||||
- column:
|
||||
name: description
|
||||
type: TEXT
|
||||
- column:
|
||||
name: epoch_id
|
||||
type: BIGINT
|
||||
constraints:
|
||||
nullable: false
|
||||
foreignKeyName: fk_artists_epoch
|
||||
references: epochs(id)
|
||||
- column:
|
||||
name: country_id
|
||||
type: BIGINT
|
||||
constraints:
|
||||
nullable: false
|
||||
foreignKeyName: fk_artists_country
|
||||
references: countries(id)
|
||||
|
||||
6
demo/src/main/resources/db/master.yml
Normal file
6
demo/src/main/resources/db/master.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
databaseChangeLog:
|
||||
- includeAll:
|
||||
path: changes/
|
||||
relativeToChangelogFile: true
|
||||
errorIfMissingOrEmpty: false
|
||||
|
||||
39
demo/src/main/resources/public/css/style.css
Normal file
39
demo/src/main/resources/public/css/style.css
Normal file
@@ -0,0 +1,39 @@
|
||||
:root {
|
||||
--punk-primary: blueviolet;
|
||||
--punk-dark: #121212;
|
||||
}
|
||||
|
||||
.text-punk {
|
||||
color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
.border-punk {
|
||||
border-color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
.bg-punk {
|
||||
background-color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
.page-link {
|
||||
background-color: transparent;
|
||||
border-color: var(--punk-primary);
|
||||
color: var(--punk-primary);
|
||||
}
|
||||
|
||||
.page-link:hover {
|
||||
background-color: var(--punk-primary);
|
||||
color: white;
|
||||
border-color: var(--punk-primary);
|
||||
}
|
||||
|
||||
.page-item.active .page-link {
|
||||
background-color: var(--punk-primary);
|
||||
border-color: var(--punk-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
39
demo/src/main/resources/static/css/style.css
Normal file
39
demo/src/main/resources/static/css/style.css
Normal file
@@ -0,0 +1,39 @@
|
||||
:root {
|
||||
--punk-primary: blueviolet;
|
||||
--punk-dark: #121212;
|
||||
}
|
||||
|
||||
.text-punk {
|
||||
color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
.border-punk {
|
||||
border-color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
.bg-punk {
|
||||
background-color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
.page-link {
|
||||
background-color: transparent;
|
||||
border-color: var(--punk-primary);
|
||||
color: var(--punk-primary);
|
||||
}
|
||||
|
||||
.page-link:hover {
|
||||
background-color: var(--punk-primary);
|
||||
color: white;
|
||||
border-color: var(--punk-primary);
|
||||
}
|
||||
|
||||
.page-item.active .page-link {
|
||||
background-color: var(--punk-primary);
|
||||
border-color: var(--punk-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
color: var(--punk-primary) !important;
|
||||
}
|
||||
|
||||
16
demo/src/main/resources/static/index.html
Normal file
16
demo/src/main/resources/static/index.html
Normal file
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="/styles.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
|
||||
<title>Панкуха</title>
|
||||
</head>
|
||||
<body class="bg-dark text-light">
|
||||
<div id="root"></div>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
43
demo/src/main/resources/templates/default.html
Normal file
43
demo/src/main/resources/templates/default.html
Normal file
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">Панк-рок исполнители</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
|
||||
<link rel="stylesheet" href="/webjars/bootstrap/5.3.3/dist/css/bootstrap.min.css" />
|
||||
<link rel="stylesheet" href="/webjars/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" />
|
||||
<link rel="stylesheet" href="/css/style.css" />
|
||||
<th:block layout:fragment="css"></th:block>
|
||||
</head>
|
||||
<body class="bg-dark text-light">
|
||||
<div class="d-flex flex-column min-vh-100">
|
||||
<header>
|
||||
<nav class="navbar navbar-expand-md navbar-dark bg-dark border-bottom border-punk">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand text-punk" href="/">
|
||||
<i class="bi bi-music-note-beamed"></i>
|
||||
Панк-рок
|
||||
</a>
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="navbar-collapse collapse justify-content-end" id="navbarNav">
|
||||
<div class="navbar-nav">
|
||||
<a class="nav-link" href="/page-artists">Исполнители</a>
|
||||
<a class="nav-link" href="/page-countries">Страны</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="flex-grow-1 container-fluid p-4" layout:fragment="content"></main>
|
||||
<footer class="d-flex flex-shrink-0 align-items-center justify-content-center bg-dark border-top border-punk py-3">
|
||||
<span class="text-muted">Панк-рок исполнители, [[${#dates.year(#dates.createNow())}]]</span>
|
||||
</footer>
|
||||
</div>
|
||||
<script type="text/javascript" src="/webjars/bootstrap/5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<th:block layout:fragment="js"></th:block>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
76
demo/src/main/resources/templates/f-artists.html
Normal file
76
demo/src/main/resources/templates/f-artists.html
Normal file
@@ -0,0 +1,76 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
<th:block th:fragment="draw (items, totalPages, currentPage)">
|
||||
<th:block th:with="isEmpty=${items.size() == 0}">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-dark table-hover table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Название</th>
|
||||
<th>Описание</th>
|
||||
<th>Эпоха</th>
|
||||
<th>Страна</th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<th:block th:if="${isEmpty}">
|
||||
<tr>
|
||||
<td class="text-center" colspan="100">
|
||||
<h5 class="text-center text-muted">Данные отсутствуют</h5>
|
||||
</td>
|
||||
</tr>
|
||||
</th:block>
|
||||
<th:block th:unless="${isEmpty}">
|
||||
<tr th:each="artist : ${items}">
|
||||
<td th:text="${artist.id}"></td>
|
||||
<td th:text="${artist.name}"></td>
|
||||
<td>
|
||||
<span th:if="${artist.description != null and artist.description.length() > 0}" th:text="${#strings.abbreviate(artist.description, 50)}"></span>
|
||||
<span th:unless="${artist.description != null and artist.description.length() > 0}" class="text-muted">-</span>
|
||||
</td>
|
||||
<td th:text="${artist.epoch?.name}"></td>
|
||||
<td th:text="${artist.country?.name}"></td>
|
||||
<td class="p-1">
|
||||
<a
|
||||
class="btn btn-warning btn-sm"
|
||||
th:href="@{/page-artists/edit/{id}(id=${artist.id},page=${currentPage})}"
|
||||
>
|
||||
<i class="bi bi-pencil-fill"></i>
|
||||
</a>
|
||||
</td>
|
||||
<td class="p-1">
|
||||
<form
|
||||
th:action="@{/page-artists/delete/{id}(id=${artist.id},page=${currentPage})}"
|
||||
method="post"
|
||||
>
|
||||
<button
|
||||
class="btn btn-danger btn-sm"
|
||||
onclick="return confirm('Вы уверены?')"
|
||||
>
|
||||
<i class="bi bi-trash-fill"></i>
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</th:block>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<th:block
|
||||
th:replace="~{ f-pagination :: draw (
|
||||
path='page-artists',
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage}) }"
|
||||
/>
|
||||
</th:block>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
67
demo/src/main/resources/templates/f-countries.html
Normal file
67
demo/src/main/resources/templates/f-countries.html
Normal file
@@ -0,0 +1,67 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
<th:block th:fragment="draw (items, totalPages, currentPage)">
|
||||
<th:block th:with="isEmpty=${items.size() == 0}">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-dark table-hover table-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Название</th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<th:block th:if="${isEmpty}">
|
||||
<tr>
|
||||
<td class="text-center" colspan="100">
|
||||
<h5 class="text-center text-muted">Данные отсутствуют</h5>
|
||||
</td>
|
||||
</tr>
|
||||
</th:block>
|
||||
<th:block th:unless="${isEmpty}">
|
||||
<tr th:each="country : ${items}">
|
||||
<td th:text="${country.id}"></td>
|
||||
<td th:text="${country.name}"></td>
|
||||
<td class="p-1">
|
||||
<a
|
||||
class="btn btn-warning btn-sm"
|
||||
th:href="@{/page-countries/edit/{id}(id=${country.id},page=${currentPage})}"
|
||||
>
|
||||
<i class="bi bi-pencil-fill"></i>
|
||||
</a>
|
||||
</td>
|
||||
<td class="p-1">
|
||||
<form
|
||||
th:action="@{/page-countries/delete/{id}(id=${country.id},page=${currentPage})}"
|
||||
method="post"
|
||||
>
|
||||
<button
|
||||
class="btn btn-danger btn-sm"
|
||||
onclick="return confirm('Вы уверены?')"
|
||||
>
|
||||
<i class="bi bi-trash-fill"></i>
|
||||
</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</th:block>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<th:block
|
||||
th:replace="~{ f-pagination :: draw (
|
||||
path='page-countries',
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage}) }"
|
||||
/>
|
||||
</th:block>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
56
demo/src/main/resources/templates/f-pagination.html
Normal file
56
demo/src/main/resources/templates/f-pagination.html
Normal file
@@ -0,0 +1,56 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title></title>
|
||||
</head>
|
||||
<body>
|
||||
<th:block th:fragment="draw (path, totalPages, currentPage)">
|
||||
<nav th:if="${totalPages > 1}" th:with="maxPage=2">
|
||||
<ul
|
||||
class="pagination justify-content-center"
|
||||
th:with="seqFrom=${currentPage - maxPage < 1 ? 1 : currentPage - maxPage},
|
||||
seqTo=${currentPage + maxPage > totalPages ? totalPages : currentPage + maxPage}"
|
||||
>
|
||||
<th:block th:if="${currentPage > maxPage + 1}">
|
||||
<li class="page-item">
|
||||
<a class="page-link" aria-label="Previous" th:href="@{/{url}(url=${path})}">
|
||||
<span aria-hidden="true">«</span>
|
||||
</a>
|
||||
</li>
|
||||
<li class="page-item disabled">
|
||||
<span class="page-link" aria-label="Previous">
|
||||
<span aria-hidden="true">…</span>
|
||||
</span>
|
||||
</li>
|
||||
</th:block>
|
||||
<li
|
||||
class="page-item"
|
||||
th:each="page : ${#numbers.sequence(seqFrom, seqTo)}"
|
||||
th:classappend="${page == currentPage} ? 'active' : ''"
|
||||
>
|
||||
<a class="page-link" th:href="@{/{url}?page={page}(url=${path},page=${page})}">
|
||||
<span th:text="${page}" />
|
||||
</a>
|
||||
</li>
|
||||
<th:block th:if="${currentPage < totalPages - maxPage}">
|
||||
<li class="page-item disabled">
|
||||
<span class="page-link" aria-label="Previous">
|
||||
<span aria-hidden="true">…</span>
|
||||
</span>
|
||||
</li>
|
||||
<li class="page-item">
|
||||
<a
|
||||
class="page-link"
|
||||
aria-label="Next"
|
||||
th:href="@{/{url}?page={page}(url=${path},page=${totalPages})}"
|
||||
>
|
||||
<span aria-hidden="true">»</span>
|
||||
</a>
|
||||
</li>
|
||||
</th:block>
|
||||
</ul>
|
||||
</nav>
|
||||
</th:block>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
86
demo/src/main/resources/templates/page-artists-edit.html
Normal file
86
demo/src/main/resources/templates/page-artists-edit.html
Normal file
@@ -0,0 +1,86 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
<title>Редактировать исполнителя</title>
|
||||
</head>
|
||||
<body>
|
||||
<main layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col-md-8">
|
||||
<form
|
||||
th:action="${artist.id == null} ? @{/page-artists/edit(page=${page})} : @{/page-artists/edit/{id}(id=${artist.id},page=${page})}"
|
||||
th:object="${artist}"
|
||||
method="post"
|
||||
>
|
||||
<div th:if="${successSave}" class="alert alert-success mb-2" role="alert">
|
||||
Данные успешно записаны
|
||||
</div>
|
||||
<div class="mb-2" th:with="hasError=${#fields.hasErrors('name')}">
|
||||
<label for="name" class="form-label">Название</label>
|
||||
<input
|
||||
type="text"
|
||||
th:field="*{name}"
|
||||
id="name"
|
||||
class="form-control bg-dark text-light"
|
||||
th:classappend="${hasError ? 'is-invalid' : ''}"
|
||||
/>
|
||||
<div th:if="${hasError}" th:errors="*{name}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-2" th:with="hasError=${#fields.hasErrors('description')}">
|
||||
<label for="description" class="form-label">Описание</label>
|
||||
<textarea
|
||||
th:field="*{description}"
|
||||
id="description"
|
||||
class="form-control bg-dark text-light"
|
||||
rows="4"
|
||||
th:classappend="${hasError ? 'is-invalid' : ''}"
|
||||
></textarea>
|
||||
<div th:if="${hasError}" th:errors="*{description}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-2" th:with="hasError=${#fields.hasErrors('epochId')}">
|
||||
<label for="epochId" class="form-label">Эпоха</label>
|
||||
<select
|
||||
th:field="*{epochId}"
|
||||
id="epochId"
|
||||
class="form-select bg-dark text-light"
|
||||
th:classappend="${hasError ? 'is-invalid' : ''}"
|
||||
>
|
||||
<option selected value="">Выберите эпоху</option>
|
||||
<option
|
||||
th:each="epoch : ${epochs}"
|
||||
th:value="${epoch.id}"
|
||||
th:selected="${epoch.id==epochId}"
|
||||
th:text="${epoch.name}"
|
||||
></option>
|
||||
</select>
|
||||
<div th:if="${hasError}" th:errors="*{epochId}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-2" th:with="hasError=${#fields.hasErrors('countryId')}">
|
||||
<label for="countryId" class="form-label">Страна</label>
|
||||
<select
|
||||
th:field="*{countryId}"
|
||||
id="countryId"
|
||||
class="form-select bg-dark text-light"
|
||||
th:classappend="${hasError ? 'is-invalid' : ''}"
|
||||
>
|
||||
<option selected value="">Выберите страну</option>
|
||||
<option
|
||||
th:each="country : ${countries}"
|
||||
th:value="${country.id}"
|
||||
th:selected="${country.id==countryId}"
|
||||
th:text="${country.name}"
|
||||
></option>
|
||||
</select>
|
||||
<div th:if="${hasError}" th:errors="*{countryId}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="text-center">
|
||||
<button class="btn btn-primary" type="submit">Сохранить</button>
|
||||
<a class="btn btn-secondary mx-2" th:href="@{/page-artists(page=${page})}">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
59
demo/src/main/resources/templates/page-artists.html
Normal file
59
demo/src/main/resources/templates/page-artists.html
Normal file
@@ -0,0 +1,59 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
<title>Исполнители</title>
|
||||
</head>
|
||||
<body>
|
||||
<main layout:fragment="content">
|
||||
<div class="mb-3">
|
||||
<a class="btn btn-primary" th:href="@{/page-artists/edit(page=${page})}">
|
||||
<i class="bi bi-plus-circle-fill me-2"></i>Создать нового исполнителя
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="card bg-dark border-punk mb-3">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title text-punk">Фильтры</h5>
|
||||
<form th:action="@{/page-artists/filter}" method="post" class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<label for="countryId" class="form-label">Страна</label>
|
||||
<select id="countryId" name="countryId" class="form-select bg-dark text-light">
|
||||
<option value="">Все страны</option>
|
||||
<option
|
||||
th:each="country : ${countries}"
|
||||
th:value="${country.id}"
|
||||
th:selected="${country.id == selectedCountryId}"
|
||||
th:text="${country.name}"
|
||||
></option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label for="epochId" class="form-label">Эпоха</label>
|
||||
<select id="epochId" name="epochId" class="form-select bg-dark text-light">
|
||||
<option value="">Все эпохи</option>
|
||||
<option
|
||||
th:each="epoch : ${epochs}"
|
||||
th:value="${epoch.id}"
|
||||
th:selected="${epoch.id == selectedEpochId}"
|
||||
th:text="${epoch.name}"
|
||||
></option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-4 d-flex align-items-end">
|
||||
<button type="submit" class="btn btn-outline-primary me-2">Применить</button>
|
||||
<a th:href="@{/page-artists/filter/clear}" class="btn btn-outline-secondary">Сбросить</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<th:block
|
||||
th:replace="~{ f-artists :: draw (
|
||||
items=${artists.items},
|
||||
totalPages=${artists.totalPages},
|
||||
currentPage=${artists.currentPage}) }"
|
||||
/>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
39
demo/src/main/resources/templates/page-countries-edit.html
Normal file
39
demo/src/main/resources/templates/page-countries-edit.html
Normal file
@@ -0,0 +1,39 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
<title>Редактировать страну</title>
|
||||
</head>
|
||||
<body>
|
||||
<main layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<form
|
||||
th:action="${country.id == null} ? @{/page-countries/edit(page=${page})} : @{/page-countries/edit/{id}(id=${country.id},page=${page})}"
|
||||
th:object="${country}"
|
||||
method="post"
|
||||
>
|
||||
<div th:if="${successSave}" class="alert alert-success mb-2" role="alert">
|
||||
Данные успешно записаны
|
||||
</div>
|
||||
<div class="mb-2" th:with="hasError=${#fields.hasErrors('name')}">
|
||||
<label for="name" class="form-label">Название</label>
|
||||
<input
|
||||
type="text"
|
||||
th:field="*{name}"
|
||||
id="name"
|
||||
class="form-control bg-dark text-light"
|
||||
th:classappend="${hasError ? 'is-invalid' : ''}"
|
||||
/>
|
||||
<div th:if="${hasError}" th:errors="*{name}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="text-center">
|
||||
<button class="btn btn-primary" type="submit">Сохранить</button>
|
||||
<a class="btn btn-secondary mx-2" th:href="@{/page-countries(page=${page})}">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
22
demo/src/main/resources/templates/page-countries.html
Normal file
22
demo/src/main/resources/templates/page-countries.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
<head>
|
||||
<title>Страны</title>
|
||||
</head>
|
||||
<body>
|
||||
<main layout:fragment="content">
|
||||
<div class="mb-2">
|
||||
<a class="btn btn-primary" th:href="@{/page-countries/edit(page=${page})}">
|
||||
<i class="bi bi-plus-circle-fill me-2"></i>Создать новую страну
|
||||
</a>
|
||||
</div>
|
||||
<th:block
|
||||
th:replace="~{ f-countries :: draw (
|
||||
items=${countries.items},
|
||||
totalPages=${countries.totalPages},
|
||||
currentPage=${countries.currentPage}) }"
|
||||
/>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class DemoApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import com.example.demo.dto.ArtistRs;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.ArtistMapper;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class ArtistServiceTests {
|
||||
@Autowired
|
||||
private ArtistService service;
|
||||
@Autowired
|
||||
private EpochService epochService;
|
||||
@Autowired
|
||||
private CountryService countryService;
|
||||
@Autowired
|
||||
private ArtistMapper mapper;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAllTest() {
|
||||
Assertions.assertNotNull(service.getAll());
|
||||
Assertions.assertTrue(service.getAll().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createTest() {
|
||||
// Создаем необходимые зависимости
|
||||
final var epochRq1 = new com.example.demo.dto.EpochRq();
|
||||
epochRq1.setName("1980-е");
|
||||
final var epoch1 = epochService.create(epochRq1);
|
||||
|
||||
final var epochRq2 = new com.example.demo.dto.EpochRq();
|
||||
epochRq2.setName("1990-е");
|
||||
final var epoch2 = epochService.create(epochRq2);
|
||||
|
||||
final var countryRq1 = new com.example.demo.dto.CountryRq();
|
||||
countryRq1.setName("Россия");
|
||||
final var country1 = countryService.create(countryRq1);
|
||||
|
||||
final var countryRq2 = new com.example.demo.dto.CountryRq();
|
||||
countryRq2.setName("США");
|
||||
final var country2 = countryService.create(countryRq2);
|
||||
|
||||
final ArtistRs artist1 = service.create(mapper.toRqDto("Artist 1", "Description 1", epoch1.getId(), country1.getId()));
|
||||
final ArtistRs artist2 = service.create(mapper.toRqDto("Artist 2", "Description 2", epoch2.getId(), country2.getId()));
|
||||
final ArtistRs artist3 = service.create(mapper.toRqDto("Artist 3", "Description 3", epoch1.getId(), country1.getId()));
|
||||
|
||||
Assertions.assertEquals(3, service.getAll().size());
|
||||
Assertions.assertNotNull(artist1.getId());
|
||||
Assertions.assertNotNull(artist2.getId());
|
||||
Assertions.assertNotNull(artist3.getId());
|
||||
|
||||
final ArtistRs cmpEntity = service.get(artist3.getId());
|
||||
Assertions.assertEquals(artist3.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(artist3.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final var allArtists = service.getAll();
|
||||
Assertions.assertFalse(allArtists.isEmpty());
|
||||
|
||||
final ArtistRs entity = allArtists.get(0);
|
||||
final Long entityId = entity.getId();
|
||||
final String oldName = entity.getName();
|
||||
final var epoch = entity.getEpoch();
|
||||
final var country = entity.getCountry();
|
||||
|
||||
final String test = "TEST ARTIST";
|
||||
final ArtistRs newEntity = service.update(entityId, mapper.toRqDto(test, "New Description", epoch.getId(), country.getId()));
|
||||
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
|
||||
final ArtistRs cmpEntity = service.get(entityId);
|
||||
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
final var allArtists = service.getAll();
|
||||
final int initialSize = allArtists.size();
|
||||
Assertions.assertTrue(initialSize > 0);
|
||||
|
||||
final ArtistRs toDelete = allArtists.get(0);
|
||||
final Long deleteId = toDelete.getId();
|
||||
|
||||
service.delete(deleteId);
|
||||
Assertions.assertEquals(initialSize - 1, service.getAll().size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import com.example.demo.dto.CountryRs;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.CountryMapper;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class CountryServiceTests {
|
||||
@Autowired
|
||||
private CountryService service;
|
||||
@Autowired
|
||||
private CountryMapper mapper;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAllTest() {
|
||||
Assertions.assertNotNull(service.getAll());
|
||||
Assertions.assertTrue(service.getAll().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createTest() {
|
||||
final CountryRs country1 = service.create(mapper.toRqDto("Россия"));
|
||||
final CountryRs country2 = service.create(mapper.toRqDto("США"));
|
||||
final CountryRs country3 = service.create(mapper.toRqDto("Тайга"));
|
||||
|
||||
Assertions.assertEquals(3, service.getAll().size());
|
||||
Assertions.assertNotNull(country1.getId());
|
||||
Assertions.assertNotNull(country2.getId());
|
||||
Assertions.assertNotNull(country3.getId());
|
||||
|
||||
final CountryRs cmpEntity = service.get(country3.getId());
|
||||
Assertions.assertEquals(country3.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(country3.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final var allCountries = service.getAll();
|
||||
Assertions.assertFalse(allCountries.isEmpty());
|
||||
|
||||
final CountryRs entity = allCountries.get(0);
|
||||
final Long entityId = entity.getId();
|
||||
final String oldName = entity.getName();
|
||||
|
||||
final String test = "TEST";
|
||||
final CountryRs newEntity = service.update(entityId, mapper.toRqDto(test));
|
||||
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
|
||||
final CountryRs cmpEntity = service.get(entityId);
|
||||
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
final var allCountries = service.getAll();
|
||||
final int initialSize = allCountries.size();
|
||||
Assertions.assertTrue(initialSize > 0);
|
||||
|
||||
final CountryRs toDelete = allCountries.get(0);
|
||||
final Long deleteId = toDelete.getId();
|
||||
|
||||
service.delete(deleteId);
|
||||
Assertions.assertEquals(initialSize - 1, service.getAll().size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
|
||||
import com.example.demo.dto.EpochRs;
|
||||
import com.example.demo.error.NotFoundException;
|
||||
import com.example.demo.mapper.EpochMapper;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
|
||||
public class EpochServiceTests {
|
||||
@Autowired
|
||||
private EpochService service;
|
||||
@Autowired
|
||||
private EpochMapper mapper;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getAllTest() {
|
||||
Assertions.assertNotNull(service.getAll());
|
||||
Assertions.assertTrue(service.getAll().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createTest() {
|
||||
final EpochRs epoch1 = service.create(mapper.toRqDto("1980-е"));
|
||||
final EpochRs epoch2 = service.create(mapper.toRqDto("1990-е"));
|
||||
final EpochRs epoch3 = service.create(mapper.toRqDto("2000-е"));
|
||||
|
||||
Assertions.assertEquals(3, service.getAll().size());
|
||||
Assertions.assertNotNull(epoch1.getId());
|
||||
Assertions.assertNotNull(epoch2.getId());
|
||||
Assertions.assertNotNull(epoch3.getId());
|
||||
|
||||
final EpochRs cmpEntity = service.get(epoch3.getId());
|
||||
Assertions.assertEquals(epoch3.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(epoch3.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final var allEpochs = service.getAll();
|
||||
Assertions.assertFalse(allEpochs.isEmpty());
|
||||
|
||||
final EpochRs entity = allEpochs.get(0);
|
||||
final Long entityId = entity.getId();
|
||||
final String oldName = entity.getName();
|
||||
|
||||
final String test = "TEST";
|
||||
final EpochRs newEntity = service.update(entityId, mapper.toRqDto(test));
|
||||
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
|
||||
final EpochRs cmpEntity = service.get(entityId);
|
||||
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
|
||||
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
final var allEpochs = service.getAll();
|
||||
final int initialSize = allEpochs.size();
|
||||
Assertions.assertTrue(initialSize > 0);
|
||||
|
||||
final EpochRs toDelete = allEpochs.get(0);
|
||||
final Long deleteId = toDelete.getId();
|
||||
|
||||
service.delete(deleteId);
|
||||
Assertions.assertEquals(initialSize - 1, service.getAll().size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
|
||||
}
|
||||
}
|
||||
|
||||
5
demo/src/test/resources/application-dev.yml
Normal file
5
demo/src/test/resources/application-dev.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:h2:mem:testdb
|
||||
driver-class-name: org.h2.Driver
|
||||
|
||||
7
demo/src/test/resources/application-prod.yml
Normal file
7
demo/src/test/resources/application-prod.yml
Normal file
@@ -0,0 +1,7 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:postgresql://127.0.0.1/demo_test
|
||||
username: postgres
|
||||
password: postgres
|
||||
driver-class-name: org.postgresql.Driver
|
||||
|
||||
2
demo/src/test/resources/application.properties
Normal file
2
demo/src/test/resources/application.properties
Normal file
@@ -0,0 +1,2 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
|
||||
14
demo/src/test/resources/application.yml
Normal file
14
demo/src/test/resources/application.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
logging:
|
||||
level:
|
||||
com:
|
||||
example:
|
||||
demo: DEBUG
|
||||
spring:
|
||||
profiles:
|
||||
active: prod
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create-drop
|
||||
liquibase:
|
||||
enabled: false
|
||||
|
||||
311
demo/РАЗБОР_ЛАБОРАТОРНОЙ_РАБОТЫ.md
Normal file
311
demo/РАЗБОР_ЛАБОРАТОРНОЙ_РАБОТЫ.md
Normal file
@@ -0,0 +1,311 @@
|
||||
# 📋 Разбор лабораторной работы по пунктам
|
||||
|
||||
## ✅ Пункт 1: Заменить два REST-контроллера на MVC-контроллеры
|
||||
|
||||
### Что было (REST-контроллеры):
|
||||
1. **`ArtistController.java`** - `@RestController`
|
||||
- Путь: `/api/artists`
|
||||
- Возвращает JSON ответы
|
||||
- Файл: `demo/src/main/java/com/example/demo/controller/ArtistController.java`
|
||||
|
||||
2. **`CountryController.java`** - `@RestController`
|
||||
- Путь: `/api/countries`
|
||||
- Возвращает JSON ответы
|
||||
- Файл: `demo/src/main/java/com/example/demo/controller/CountryController.java`
|
||||
|
||||
### Что стало (MVC-контроллеры):
|
||||
1. **`ArtistMvcController.java`** - `@Controller`
|
||||
- Путь: `/page-artists`
|
||||
- Возвращает имена Thymeleaf шаблонов (например, `"page-artists"`)
|
||||
- Файл: `demo/src/main/java/com/example/demo/controller/mvc/ArtistMvcController.java`
|
||||
- ❗ **ВАЖНО**: REST-контроллер **НЕ УДАЛЁН** - он остался для React приложения
|
||||
|
||||
2. **`CountryMvcController.java`** - `@Controller`
|
||||
- Путь: `/page-countries`
|
||||
- Возвращает имена Thymeleaf шаблонов (например, `"page-countries"`)
|
||||
- Файл: `demo/src/main/java/com/example/demo/controller/mvc/CountryMvcController.java`
|
||||
- ❗ **ВАЖНО**: REST-контроллер **НЕ УДАЛЁН** - он остался для React приложения
|
||||
|
||||
### Отличия:
|
||||
- **REST**: `@RestController` → возвращает JSON (для API)
|
||||
- **MVC**: `@Controller` → возвращает имя шаблона (для HTML страниц)
|
||||
|
||||
---
|
||||
|
||||
## ✅ Пункт 2: MVC-контроллер с функциями помимо CRUD
|
||||
|
||||
### Контроллер: `ArtistMvcController`
|
||||
|
||||
### Стандартные CRUD операции:
|
||||
1. ✅ **Create** (Создать):
|
||||
- `GET /page-artists/edit` - форма создания (строка 110)
|
||||
- `POST /page-artists/edit` - сохранить нового артиста (строка 120)
|
||||
|
||||
2. ✅ **Read** (Читать):
|
||||
- `GET /page-artists` - список всех артистов (строка 58)
|
||||
- `GET /page-artists/edit/{id}` - форма редактирования (строка 139)
|
||||
|
||||
3. ✅ **Update** (Обновить):
|
||||
- `POST /page-artists/edit/{id}` - сохранить изменения (строка 149)
|
||||
|
||||
4. ✅ **Delete** (Удалить):
|
||||
- `POST /page-artists/delete/{id}` - удалить артиста (строка 169)
|
||||
|
||||
### ➕ Функции ПОМИМО CRUD:
|
||||
|
||||
1. **Фильтрация артистов** (строки 92-101):
|
||||
- `POST /page-artists/filter` - применить фильтры (по стране и эпохе)
|
||||
- Использует сессионный бин `ArtistFilterSession` для сохранения фильтров
|
||||
|
||||
2. **Очистка фильтров** (строки 103-108):
|
||||
- `GET /page-artists/filter/clear` - сбросить все фильтры
|
||||
|
||||
3. **Фильтрованный список** (строки 66-76):
|
||||
- Метод `getAll()` использует `artistService.getAllFiltered()`
|
||||
- Фильтрует по `countryId` и `epochId` из сессии
|
||||
- Это **не стандартный CRUD**, а дополнительная бизнес-логика
|
||||
|
||||
### Где это используется:
|
||||
- В шаблоне `page-artists.html` (строки 17-48) - форма фильтрации
|
||||
- Фильтры сохраняются между переходами по страницам (пагинация)
|
||||
|
||||
---
|
||||
|
||||
## ✅ Пункт 3: Thymeleaf-шаблоны для генерации HTML-страниц
|
||||
|
||||
### Для `ArtistMvcController`:
|
||||
|
||||
1. **`page-artists.html`** - главная страница списка артистов
|
||||
- Путь: `demo/src/main/resources/templates/page-artists.html`
|
||||
- Используется в: `return VIEW;` где `VIEW = "page-artists"` (строка 89)
|
||||
- Содержит: список артистов, фильтры, пагинацию
|
||||
|
||||
2. **`page-artists-edit.html`** - форма создания/редактирования
|
||||
- Путь: `demo/src/main/resources/templates/page-artists-edit.html`
|
||||
- Используется в: `return VIEW_EDIT;` где `VIEW_EDIT = "page-artists-edit"` (строки 117, 146)
|
||||
- Содержит: форму с полями (название, описание, эпоха, страна)
|
||||
|
||||
3. **`f-artists.html`** - фрагмент для отображения таблицы артистов
|
||||
- Путь: `demo/src/main/resources/templates/f-artists.html`
|
||||
- Используется в: `page-artists.html` (строка 50-55) через `th:replace`
|
||||
|
||||
### Для `CountryMvcController`:
|
||||
|
||||
1. **`page-countries.html`** - главная страница списка стран
|
||||
- Путь: `demo/src/main/resources/templates/page-countries.html`
|
||||
- Используется в: `return VIEW;` где `VIEW = "page-countries"` (строка 57)
|
||||
|
||||
2. **`page-countries-edit.html`** - форма создания/редактирования
|
||||
- Путь: `demo/src/main/resources/templates/page-countries-edit.html`
|
||||
- Используется в: `return VIEW_EDIT;` где `VIEW_EDIT = "page-countries-edit"` (строки 65, 90)
|
||||
|
||||
3. **`f-countries.html`** - фрагмент для отображения таблицы стран
|
||||
- Путь: `demo/src/main/resources/templates/f-countries.html`
|
||||
- Используется в: `page-countries.html` (строка 13-18) через `th:replace`
|
||||
|
||||
### Общие шаблоны:
|
||||
|
||||
1. **`default.html`** - базовый layout (навигация, header, footer)
|
||||
- Путь: `demo/src/main/resources/templates/default.html`
|
||||
- Все страницы наследуют через `layout:decorate="~{default}"`
|
||||
|
||||
2. **`f-pagination.html`** - фрагмент пагинации
|
||||
- Путь: `demo/src/main/resources/templates/f-pagination.html`
|
||||
- Используется в `f-artists.html` и `f-countries.html`
|
||||
|
||||
### Как это работает:
|
||||
1. Контроллер возвращает имя шаблона (например, `"page-artists"`)
|
||||
2. Spring Boot ищет файл `templates/page-artists.html`
|
||||
3. Thymeleaf обрабатывает шаблон и генерирует HTML
|
||||
4. HTML отправляется браузеру
|
||||
|
||||
---
|
||||
|
||||
## ✅ Пункт 4: Функция пагинации
|
||||
|
||||
### Где реализовано:
|
||||
|
||||
#### 1. В контроллерах:
|
||||
- **`ArtistMvcController.getAll()`** (строки 58-89):
|
||||
- Принимает параметры `page` (по умолчанию 1) и `size` (по умолчанию 3)
|
||||
- Использует `PageHelper.toPageable(page, size)` для создания объекта пагинации
|
||||
- Возвращает `PageRs<ArtistRs>` с информацией: `totalPages`, `currentPage`, `items`
|
||||
|
||||
- **`CountryMvcController.getAll()`** (строки 44-58):
|
||||
- Принимает параметры `page` (по умолчанию 1) и `size` (по умолчанию 3)
|
||||
- Аналогично возвращает `PageRs<CountryRs>`
|
||||
|
||||
#### 2. В сервисах:
|
||||
- **`ArtistService.getAllFiltered()`** (строка 48):
|
||||
- Использует Spring Data `Pageable` для запроса к БД
|
||||
- Возвращает `Page<ArtistEntity>`, который конвертируется в `PageRs<ArtistRs>`
|
||||
|
||||
#### 3. В шаблонах:
|
||||
- **`f-pagination.html`** - фрагмент с кнопками пагинации
|
||||
- Принимает: `path` (URL), `totalPages`, `currentPage`
|
||||
- Отображает: кнопки с номерами страниц, кнопки "назад/вперед"
|
||||
- Показывается только если `totalPages > 1`
|
||||
|
||||
- **`f-artists.html`** (строки 66-71):
|
||||
- Вызывает фрагмент пагинации:
|
||||
```html
|
||||
<th:block th:replace="~{f-pagination :: draw(
|
||||
path='page-artists',
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage})}" />
|
||||
```
|
||||
|
||||
- **`f-countries.html`** (строки 57-62):
|
||||
- Аналогично вызывает фрагмент пагинации для стран
|
||||
|
||||
### Как это работает:
|
||||
1. Пользователь открывает `/page-artists` (по умолчанию `page=1`)
|
||||
2. Контроллер получает запрос, создаёт `Pageable` объект
|
||||
3. Сервис запрашивает данные из БД с пагинацией (LIMIT/OFFSET)
|
||||
4. В модель добавляется `PageRs` с информацией о страницах
|
||||
5. Thymeleaf отображает кнопки пагинации внизу таблицы
|
||||
6. При клике на кнопку - новый запрос с другим `page` параметром
|
||||
|
||||
### Пример URL:
|
||||
- Страница 1: `/page-artists?page=1`
|
||||
- Страница 2: `/page-artists?page=2`
|
||||
- Страница 3: `/page-artists?page=3`
|
||||
|
||||
---
|
||||
|
||||
## ✅ Пункт 5: Сессионная переменная и сессионный компонент (бин)
|
||||
|
||||
### 1. Сессионный компонент (бин):
|
||||
|
||||
**Файл**: `demo/src/main/java/com/example/demo/controller/mvc/ArtistFilterSession.java`
|
||||
|
||||
```java
|
||||
@Component
|
||||
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||
public class ArtistFilterSession {
|
||||
private Long countryId;
|
||||
private Long epochId;
|
||||
// ... геттеры, сеттеры, методы clearFilters()
|
||||
}
|
||||
```
|
||||
|
||||
**Что это:**
|
||||
- `@Component` - Spring бин
|
||||
- `@Scope(SCOPE_SESSION)` - создаётся один экземпляр на каждую HTTP сессию
|
||||
- `proxyMode = TARGET_CLASS` - используется CGLIB прокси для работы с сессией
|
||||
|
||||
**Где используется:**
|
||||
- В `ArtistMvcController` (строка 45):
|
||||
```java
|
||||
private final ArtistFilterSession filterSession;
|
||||
```
|
||||
- При установке фильтров (строки 67, 70, 97, 98):
|
||||
```java
|
||||
filterSession.setCountryId(countryId);
|
||||
filterSession.setEpochId(epochId);
|
||||
```
|
||||
- При получении фильтров (строки 74, 75, 86, 87):
|
||||
```java
|
||||
filterSession.getCountryId()
|
||||
filterSession.getEpochId()
|
||||
```
|
||||
|
||||
**Зачем нужно:**
|
||||
- Фильтры сохраняются между запросами в рамках одной сессии
|
||||
- При переходе на другую страницу пагинации фильтры не теряются
|
||||
- При сбросе фильтров (строка 105): `filterSession.clearFilters()`
|
||||
|
||||
### 2. Сессионные переменные (`@SessionAttributes`):
|
||||
|
||||
#### В `ArtistMvcController` (строка 29):
|
||||
```java
|
||||
@SessionAttributes(ArtistMvcController.ATR_COUNTRIES)
|
||||
```
|
||||
|
||||
**Что хранится:**
|
||||
- `ATR_COUNTRIES = "countries"` - список всех стран (строка 84)
|
||||
|
||||
**Зачем нужно:**
|
||||
- Список стран сохраняется в сессии, чтобы не загружать из БД каждый раз
|
||||
- Используется в формах редактирования для выпадающих списков
|
||||
|
||||
#### В `CountryMvcController` (строка 27):
|
||||
```java
|
||||
@SessionAttributes(CountryMvcController.ATR_COUNTRIES)
|
||||
```
|
||||
|
||||
**Что хранится:**
|
||||
- `ATR_COUNTRIES = "countries"` - список стран с пагинацией (строка 54)
|
||||
|
||||
### Управление сессионными переменными:
|
||||
|
||||
**Добавление в сессию** (строки 84, 54):
|
||||
```java
|
||||
model.addAttribute(ATR_COUNTRIES, countryService.getAll());
|
||||
```
|
||||
|
||||
**Очистка сессии** (строки 88, 56):
|
||||
```java
|
||||
sessionStatus.setComplete();
|
||||
```
|
||||
|
||||
### Разница между ними:
|
||||
|
||||
| | Сессионный бин | Сессионная переменная |
|
||||
|---|---|---|
|
||||
| **Где объявлено** | `@Component` + `@Scope(SESSION)` | `@SessionAttributes` на контроллере |
|
||||
| **Что хранит** | Свои поля (countryId, epochId) | Атрибуты модели (countries) |
|
||||
| **Управление** | Автоматически Spring | Вручную через `model.addAttribute()` |
|
||||
| **Очистка** | При завершении сессии | Через `sessionStatus.setComplete()` |
|
||||
| **Использование** | Инжектится как зависимость | Доступна через Model |
|
||||
|
||||
---
|
||||
|
||||
## 📍 Итоговая таблица соответствия требованиям:
|
||||
|
||||
| Требование | Реализовано | Где |
|
||||
|---|---|---|
|
||||
| Заменить REST на MVC | ✅ | `ArtistMvcController`, `CountryMvcController` |
|
||||
| Функции помимо CRUD | ✅ | Фильтрация в `ArtistMvcController` |
|
||||
| Thymeleaf шаблоны | ✅ | `page-*.html`, `f-*.html` в `templates/` |
|
||||
| Пагинация | ✅ | Параметры `page/size`, фрагмент `f-pagination.html` |
|
||||
| Сессионный бин | ✅ | `ArtistFilterSession.java` |
|
||||
| Сессионная переменная | ✅ | `@SessionAttributes` в обоих контроллерах |
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Где что находится:
|
||||
|
||||
### Контроллеры:
|
||||
- `demo/src/main/java/com/example/demo/controller/mvc/ArtistMvcController.java`
|
||||
- `demo/src/main/java/com/example/demo/controller/mvc/CountryMvcController.java`
|
||||
|
||||
### Сессионный компонент:
|
||||
- `demo/src/main/java/com/example/demo/controller/mvc/ArtistFilterSession.java`
|
||||
|
||||
### Шаблоны:
|
||||
- `demo/src/main/resources/templates/page-artists.html`
|
||||
- `demo/src/main/resources/templates/page-artists-edit.html`
|
||||
- `demo/src/main/resources/templates/page-countries.html`
|
||||
- `demo/src/main/resources/templates/page-countries-edit.html`
|
||||
- `demo/src/main/resources/templates/f-artists.html`
|
||||
- `demo/src/main/resources/templates/f-countries.html`
|
||||
- `demo/src/main/resources/templates/f-pagination.html`
|
||||
- `demo/src/main/resources/templates/default.html`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Как это работает вместе:
|
||||
|
||||
1. Пользователь открывает `/page-artists`
|
||||
2. `ArtistMvcController.getAll()` вызывается
|
||||
3. Используется `ArtistFilterSession` для получения сохранённых фильтров
|
||||
4. Запрашиваются данные из БД с пагинацией
|
||||
5. Данные добавляются в `Model` (включая сессионные переменные)
|
||||
6. Возвращается имя шаблона `"page-artists"`
|
||||
7. Thymeleaf обрабатывает шаблон `page-artists.html`
|
||||
8. HTML отправляется браузеру
|
||||
9. При клике на фильтр - сохраняется в сессионном бине
|
||||
10. При переходе на другую страницу - фильтры сохраняются
|
||||
|
||||
Все требования выполнены! ✅
|
||||
43
grob.html
43
grob.html
@@ -1,43 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<head>
|
||||
<title>Гражданская оборона</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Здесь можно почитать инфу про исполнителя и перейти на песню</p>
|
||||
<img src = "grob.jpg" alt="Гражданская оборона" width= 500>
|
||||
<div class="descriptionForSong">
|
||||
<p>
|
||||
«Гражданская Оборона» — культовая советская и российская рок-группа, основанная в 1984 году в Омске Егором Летовым.
|
||||
Коллектив стал одним из самых влиятельных в андеграундной среде, а его творчество оказало огромное влияние
|
||||
на развитие русского рока. Группа известна своими резкими, часто провокационными текстами, которые затрагивали
|
||||
темы социального протеста, экзистенциальных переживаний и критики общества.
|
||||
</p>
|
||||
<p>
|
||||
Музыка «Гражданской Обороны» сочетает в себе элементы панк-рока, гаражного рока и лоу-фая.
|
||||
Несмотря на минималистичный подход к звучанию, группа смогла создать уникальный стиль, который
|
||||
стал узнаваемым и вдохновил множество последующих исполнителей.
|
||||
</p>
|
||||
<p>
|
||||
Среди самых известных альбомов группы — «Тоталитаризм», «Мышеловка», «Здорово и вечно»,
|
||||
«Русское поле экспериментов» и «Инструкция по выживанию». Творчество «Гражданской Обороны»
|
||||
остается актуальным и по сей день, а Егор Летов считается одной из ключевых фигур в истории
|
||||
русской рок-музыки.
|
||||
</p>
|
||||
</div>
|
||||
<p>
|
||||
Песни:
|
||||
<ul>
|
||||
<li><a href = "grobKaifIliBolshe.html">Кайф или больше</a></li>
|
||||
<li><a href = "">Зоопарк</a></li>
|
||||
<li><a href = "">Новая патриотическая</a></li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<a href="index.html"> Вернуться назад</a>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,49 +0,0 @@
|
||||
//grobKaifIliBolshe
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<head>
|
||||
<title>Гражданская оборона - "Кайф или больше"</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h3>Тут будет типа песня</h3>
|
||||
<img src = "nekrofilia.jpg" alt = "Обложка" width="500" >
|
||||
<h2>Кайф или больше</h2>
|
||||
<a href="grob.html">Гражданская оборона</a>
|
||||
<p>Описание</p>
|
||||
<ul>
|
||||
<li>Была выпущена в 1987 году</li>
|
||||
<li>Входит в альбом некрофилия</li>
|
||||
</ul>
|
||||
<div class = "text">
|
||||
<p>Текст песни:
|
||||
<br> [Куплет 1]
|
||||
<br>Рука повисла в небе, полном до краёв
|
||||
<br>Мои ошибки устилают мой позор
|
||||
<br>Я сочно благодарен, словно кошкин блёв
|
||||
<br>И смачно богомолен, словно приговор
|
||||
|
||||
<br>[Припев]
|
||||
<br>Но мне придётся выбирать
|
||||
<br>Кайф или больше
|
||||
<br>Рай или больше
|
||||
<br>Свет или больше… Хей-йо
|
||||
|
||||
<br>[Куплет 2]
|
||||
<br>Я буду ласковым, как тёплый банный лист
|
||||
<br>Я буду вежливым, как битое окно
|
||||
<br>Я буду благотворен, словно онанист
|
||||
<br>Я буду зазеркален, словно всё равно
|
||||
|
||||
<br>[Припев]
|
||||
<br>Но мне придётся выбирать
|
||||
<br>Кайф или больше
|
||||
<br>Рай или больше
|
||||
<br>Свет или больше...хей-йо
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
<a href="index.html"> Вернуться назад</a>
|
||||
|
||||
</html>
|
||||
28
index.html
28
index.html
@@ -1,28 +0,0 @@
|
||||
//index
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
<title>Панкуха</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1>Стриминговый сервис <em>"Панкуха"</em></h1>
|
||||
<img src="res/logo.png" alt="Эмблема" width="200">
|
||||
<div class="main">
|
||||
<div class="description">
|
||||
<p><span style="background-color: blueviolet;">Какие страницы я реализовал:</span></p>
|
||||
</div>
|
||||
<ol class = "spisok">
|
||||
<a href="index.html"><li class="spisok_el">Главная страница</li></a>
|
||||
<a href="grob.html"><li>Страница исполнителя</li></a>
|
||||
<li><a href="grobKaifIliBolshe.html">Страница песни</a></li>
|
||||
<a href="catalog.html"><li>Каталог</li></a>
|
||||
<a href="punkrock.html"><li>Страница каталога</li></a>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
23
punkrock-react/.gitignore
vendored
Normal file
23
punkrock-react/.gitignore
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
70
punkrock-react/README.md
Normal file
70
punkrock-react/README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
|
||||
|
||||
The page will reload when you make changes.\
|
||||
You may also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
|
||||
|
||||
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
|
||||
|
||||
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
|
||||
### Code Splitting
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
|
||||
|
||||
### Analyzing the Bundle Size
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
|
||||
|
||||
### Making a Progressive Web App
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
|
||||
|
||||
### Advanced Configuration
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
|
||||
|
||||
### Deployment
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
|
||||
|
||||
### `npm run build` fails to minify
|
||||
|
||||
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
||||
17884
punkrock-react/package-lock.json
generated
Normal file
17884
punkrock-react/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
47
punkrock-react/package.json
Normal file
47
punkrock-react/package.json
Normal file
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "punkrock-react",
|
||||
"version": "0.1.0",
|
||||
"homepage": "/punkrock",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"bootstrap": "^5.3.6",
|
||||
"bootstrap-icons": "^1.13.1",
|
||||
"react": "^18.2.0",
|
||||
"react-bootstrap": "^2.10.2",
|
||||
"react-bootstrap-icons": "^1.11.6",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^7.6.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {}
|
||||
}
|
||||
78
punkrock-react/public/catalog.html
Normal file
78
punkrock-react/public/catalog.html
Normal file
@@ -0,0 +1,78 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="src/styles.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
|
||||
<title>Панкуха</title>
|
||||
</head>
|
||||
<body class="bg-dark text-light">
|
||||
<header class="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
|
||||
<div class="container-fluid">
|
||||
<a href="/" class="navbar-brand d-flex align-items-center ms-3">
|
||||
<img src="/res/logo.png" alt="Панкуха" height="60" class="me-2">
|
||||
<span class="text-punk fs-4 fw-bold">Панкуха</span>
|
||||
</a>
|
||||
<button class="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse bg-black" id="navbarContent">
|
||||
<ul class="navbar-nav w-100 justify-content-end pe-4">
|
||||
<li class="nav-item dropdown">
|
||||
<a class="nav-link text-punk fw-bold dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
|
||||
<i class="bi bi-list me-1"></i>Страницы
|
||||
</a>
|
||||
<ul class="dropdown-menu dropdown-menu-end bg-dark">
|
||||
<li><a class="dropdown-item text-punk" href="/">Главная</a></li>
|
||||
<li><a class="dropdown-item text-punk" href="/grob">Исполнитель</a></li>
|
||||
<li><a class="dropdown-item text-punk" href="/grobKaifIliBolshe">Песня</a></li>
|
||||
<li><a class="dropdown-item text-punk" href="/catalog">Каталог</a></li>
|
||||
<li><a class="dropdown-item text-punk" href="/punkrock">Список исполнителей</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
|
||||
<i class="bi bi-people-fill me-1"></i>Контакты
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="container-fluid my-5 flex-grow-1">
|
||||
<div class="container">
|
||||
<div class="card bg-dark border-punk mb-4">
|
||||
<div class="card-body">
|
||||
<h3 class="text-punk mb-0"><a class="text-punk" href="/punkrock">Панк-Рок</a></h3>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card bg-dark border-punk mb-4">
|
||||
<div class="card-body">
|
||||
<h3 class="text-punk mb-0">Психоделика</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card bg-dark border-punk">
|
||||
<div class="card-body">
|
||||
<h3 class="text-punk mb-0">Гаражный панк</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="bg-black py-3 border-top border-punk mt-auto">
|
||||
<div class="container">
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-center">
|
||||
<p class="mb-0 text-punk">© 2025. Все права защищены.</p>
|
||||
<nav class="d-flex align-items-center">
|
||||
<a href="#" class="text-punk me-3">Политика конфиденциальности</a>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
BIN
punkrock-react/public/favicon.ico
Normal file
BIN
punkrock-react/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user