Lab 3 Finish

This commit is contained in:
shadowik 2023-03-21 14:52:01 +04:00
commit 64360fee8c
23 changed files with 2175 additions and 0 deletions

37
.gitignore vendored Normal file
View 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/

28
build.gradle Normal file
View File

@ -0,0 +1,28 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.4'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
data.mv.db Normal file

Binary file not shown.

1014
data.trace.db Normal file

File diff suppressed because it is too large Load Diff

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
gradlew vendored Executable file
View File

@ -0,0 +1,240 @@
#!/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.
#
##############################################################################
#
# 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/master/subprojects/plugins/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
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# 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"'
# 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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# 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
which java >/dev/null 2>&1 || 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
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

91
gradlew.bat vendored Normal file
View File

@ -0,0 +1,91 @@
@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
@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=.
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.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
: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

1
settings.gradle Normal file
View File

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

View File

@ -0,0 +1,15 @@
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

View File

@ -0,0 +1,12 @@
package com.example.demo;
import org.springframework.context.annotation.Configuration;
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(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,81 @@
package com.example.demo.master;
import com.example.demo.order.MastersOrders;
import jakarta.persistence.*;
import java.util.List;
import java.util.Objects;
@Entity
public class Master {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long _id;
@Column()
private String firstName;
private String lastName;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "master", cascade = CascadeType.REMOVE)
private List<MastersOrders> mastersOrders;
public Master() {
}
public Master(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Long get_id() {
return _id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Master master = (Master) o;
return Objects.equals(_id, master._id);
}
@Override
public int hashCode() {
return Objects.hash(_id);
}
@Override
public String toString() {
return "Master{" +
"id=" + _id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
public List<MastersOrders> getOrders() {
return mastersOrders;
}
public void setOrder(MastersOrders mastersOrders) {
if (mastersOrders.getMaster().equals(this)) {
this.mastersOrders.add(mastersOrders);
}
}
}

View File

@ -0,0 +1,52 @@
package com.example.demo.master;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.RestController;
import java.util.List;
@RestController
@RequestMapping("/master")
public class MasterController {
private final MasterService masterService;
@Autowired
public MasterController(MasterService masterService) {
this.masterService = masterService;
}
@GetMapping("/{id}")
public Master getMaster(@PathVariable Long id) {
return masterService.findMaster(id);
}
@GetMapping("/")
public List<Master> getMaster() {
return masterService.findAllMasters();
}
@PostMapping("/")
public Master createMaster(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName) {
return masterService.addMaster(firstName, lastName);
}
@PatchMapping("/{id}")
public Master updateMaster(@PathVariable Long id,
@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName) {
return masterService.updateMaster(id, firstName, lastName);
}
@DeleteMapping("/{id}")
public Master deleteMaster(@PathVariable Long id) {
return masterService.deleteMaster(id);
}
}

View File

@ -0,0 +1,67 @@
package com.example.demo.master;
import com.example.demo.order.MastersOrders;
import com.example.demo.product.Product;
import jakarta.persistence.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class MasterService {
@PersistenceContext
private EntityManager em;
@Transactional
public Master addMaster(String firstName, String lastName) {
if (!StringUtils.hasText(firstName) || !StringUtils.hasText(lastName)) {
throw new IllegalArgumentException("Master name is null or empty");
}
final Master master = new Master(firstName, lastName);
em.persist(master);
return master;
}
@Transactional(readOnly = true)
public Master findMaster(Long id) {
final Master master = em.find(Master.class, id);
if (master == null) {
throw new EntityNotFoundException(String.format("Master with id [%s] is not found", id));
}
return master;
}
@Transactional(readOnly = true)
public List<Master> findAllMasters() {
return em.createQuery("select s from Master s", Master.class)
.getResultList();
}
@Transactional
public Master updateMaster(Long id, String firstName, String lastName) {
if (!StringUtils.hasText(firstName) || !StringUtils.hasText(lastName)) {
throw new IllegalArgumentException("Master name is null or empty");
}
final Master currentMaster = findMaster(id);
currentMaster.setFirstName(firstName);
currentMaster.setLastName(lastName);
return em.merge(currentMaster);
}
@Transactional
public Master deleteMaster(Long id) {
final Master currentMaster = findMaster(id);
em.remove(currentMaster);
return currentMaster;
}
@Transactional
public void deleteAllMasters() {
em.createQuery("delete from Master").executeUpdate();
}
}

View File

@ -0,0 +1,91 @@
package com.example.demo.order;
import com.example.demo.master.Master;
import com.example.demo.product.Product;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Entity
public class MastersOrders {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long _id;
@Column
private Date dateOfPurchase;
@ManyToOne(fetch = FetchType.EAGER)
private Master master;
@ManyToMany(fetch = FetchType.EAGER)
private List<Product> products;
public MastersOrders() {
}
public MastersOrders(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public Long get_id() {
return _id;
}
public Date getDateOfPurchase() {
return dateOfPurchase;
}
public void setDateOfPurchase(Date dateOfPurchase) {
this.dateOfPurchase = dateOfPurchase;
}
public void addProduct(Product product) {
if (products == null)
products = new ArrayList<>();
products.add(product);
if (product.getOrders() == null) {
product.setOrder(this);
}
}
public Master getMaster() {
return master;
}
public void setMaster(Master master) {
this.master = master;
if (!master.getOrders().contains(this)) {
master.setOrder(this);
}
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MastersOrders mastersOrders = (MastersOrders) o;
return Objects.equals(_id, mastersOrders._id);
}
@Override
public int hashCode() {
return Objects.hash(_id);
}
@Override
public String toString() {
return "Order {" +
"id=" + _id +
", date='" + dateOfPurchase.toString() + '\'' +
", customer='" + master.toString() + '\'';
}
}

View File

@ -0,0 +1,4 @@
package com.example.demo.order;
public class OrderController {
}

View File

@ -0,0 +1,86 @@
package com.example.demo.order;
import com.example.demo.master.Master;
import com.example.demo.product.Product;
import jakarta.persistence.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Service
public class OrderService {
@PersistenceContext
private EntityManager em;
@Transactional
public MastersOrders addOrder(Master master) {
if (master == null || em.find(Master.class, master.get_id()) == null) {
throw new IllegalArgumentException("addOrder empty fields");
}
final MastersOrders order = new MastersOrders(new Date(System.currentTimeMillis()));
order.setMaster(master);
em.persist(order);
em.merge(master);
return order;
}
@Transactional
public MastersOrders addProduct(Long id, Product product) {
if (product == null) {
throw new IllegalArgumentException("addOrder empty fields");
}
final MastersOrders currentOrder = findOrder(id);
currentOrder.addProduct(product);
product.setOrder(currentOrder);
em.merge(product);
return em.merge(currentOrder);
}
@Transactional()
public MastersOrders findOrder(Long id) {
final MastersOrders order = em.find(MastersOrders.class, id);
if (order == null) {
throw new EntityNotFoundException(String.format("Order with id [%s] is not found", id));
}
return order;
}
@Transactional(readOnly = true)
public List<MastersOrders> findAllOrders() {
return em.createQuery("select o from MastersOrders o", MastersOrders.class)
.getResultList();
}
@Transactional
public MastersOrders deleteOrder(Long id) {
final MastersOrders currentOrder = findOrder(id);
em.remove(currentOrder);
return currentOrder;
}
@Transactional
public MastersOrders deleteProductsInOrder(Long id, Product product) {
final MastersOrders currentOrder = findOrder(id);
final Product currentProduct = em.find(Product.class, product.get_id());
currentOrder.getProducts().remove(currentProduct);
currentProduct.getOrders().remove(currentOrder);
em.merge(currentProduct);
return em.merge(currentOrder);
}
@Transactional
public void deleteAllOrders() {
em.createQuery("delete from MastersOrders").executeUpdate();
}
@Transactional
public List<MastersOrders> findOrdersWithProduct(Long masterId, Product product) {
return em.createQuery("SELECT o FROM MastersOrders o WHERE (o.master._id = :masterId) and (:product member OF o.products)",
MastersOrders.class)
.setParameter("product", product)
.setParameter("masterId", masterId)
.getResultList();
}
}

View File

@ -0,0 +1,81 @@
package com.example.demo.product;
import com.example.demo.order.MastersOrders;
import jakarta.persistence.*;
import java.util.List;
import java.util.Objects;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long _id;
@Column()
private String _name;
private Integer cost;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "products")
private List<MastersOrders> mastersOrders;
public Product() {
}
public Product(String _name, Integer cost) {
this._name = _name;
this.cost = cost;
}
public Long get_id() {
return _id;
}
public String getName() {
return _name;
}
public void setName(String _name) {
this._name = _name;
}
public Integer getCost() {
return cost;
}
public void setCost(Integer cost) {
this.cost = cost;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return Objects.equals(_id, product._id);
}
@Override
public int hashCode() {
return Objects.hash(_id);
}
@Override
public String toString() {
return "Product {" +
"id=" + _id +
", firstName='" + _name + '\'' +
", cost='" + cost.toString() + '\'' +
'}';
}
public List<MastersOrders> getOrders() {
return mastersOrders;
}
public void setOrder(MastersOrders mastersOrders) {
if (!mastersOrders.getProducts().contains(this)) {
mastersOrders.getProducts().add(this);
}
}
}

View File

@ -0,0 +1,51 @@
package com.example.demo.product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.RestController;
import java.util.List;
@RestController
@RequestMapping("/product")
public class ProductController {
private final ProductService masterService;
@Autowired
public ProductController(ProductService masterService) {
this.masterService = masterService;
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return masterService.findProduct(id);
}
@GetMapping("/")
public List<Product> getProduct() {
return masterService.findAllProducts();
}
@PostMapping("/")
public Product createProduct(@RequestParam("name") String name,
@RequestParam("cost") Integer cost) {
return masterService.addProduct(name, cost);
}
@PatchMapping("/{id}")
public Product updateProduct(@PathVariable Long id,
@RequestParam("name") String name,
@RequestParam("cost") Integer cost) {
return masterService.updateProduct(id, name, cost);
}
@DeleteMapping("/{id}")
public Product deleteProduct(@PathVariable Long id) {
return masterService.deleteProduct(id);
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.product;
import jakarta.persistence.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class ProductService {
@PersistenceContext
private EntityManager em;
@Transactional
public Product addProduct(String name, Integer cost) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Product name is null or empty");
}
if (cost < 0) {
throw new IllegalArgumentException("Product cost is below 0");
}
final Product product = new Product(name, cost);
em.persist(product);
return product;
}
@Transactional(readOnly = true)
public Product findProduct(Long id) {
final Product product = em.find(Product.class, id);
if (product == null) {
throw new EntityNotFoundException(String.format("Product with id [%s] is not found", id));
}
return product;
}
@Transactional(readOnly = true)
public List<Product> findAllProducts() {
return em.createQuery("select s from Product s", Product.class)
.getResultList();
}
@Transactional
public Product updateProduct(Long id, String name, Integer cost) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Product name is null or empty");
}
if (cost < 0) {
throw new IllegalArgumentException("Product cost is below 0");
}
final Product currentProduct = findProduct(id);
currentProduct.setName(name);
currentProduct.setCost(cost);
return em.merge(currentProduct);
}
@Transactional
public Product deleteProduct(Long id) {
final Product currentProduct = findProduct(id);
em.remove(currentProduct);
return currentProduct;
}
@Transactional
public void deleteAllProducts() {
em.createQuery("delete from Product ").executeUpdate();
}
}

View File

@ -0,0 +1,11 @@
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +1,134 @@
package com.example.demo;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.order.*;
import com.example.demo.master.*;
import com.example.demo.product.*;
import java.util.List;
import java.util.logging.Logger;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private MasterService masterService;
@Autowired
private ProductService productService;
@Autowired
private OrderService orderService;
@Test
void testOrder() {
productService.deleteAllProducts();
orderService.deleteAllOrders();
masterService.deleteAllMasters();
final Product product1 = productService.addProduct("Машинка", 300);
final Product product2 = productService.addProduct("Ключ", 200);
final Master master1 = masterService.addMaster("Кирилл", "Петрович");
final MastersOrders order0 = orderService.addOrder(masterService.findMaster(master1.get_id()));
final MastersOrders order1 = orderService.findOrder(order0.get_id());
Assertions.assertEquals(order0, order1);
Assertions.assertEquals(masterService
.findMaster(master1.get_id()).getOrders().size(), 1);
orderService.deleteAllOrders();
Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(-1L));
final Master customer2 = masterService.addMaster("Александр", "Игоревич");
final MastersOrders order2 = orderService
.addOrder(masterService.findMaster(customer2.get_id()));
orderService.addProduct(order2.get_id(), product1);
orderService.addProduct(order2.get_id(), product1);
orderService.deleteProductsInOrder(order2.get_id(), product1);
Assertions.assertEquals(orderService
.findOrder(order2.get_id()).getProducts().size(), 1);
masterService.deleteMaster(customer2.get_id());
Assertions.assertThrows(EntityNotFoundException.class, () -> masterService.findMaster(customer2.get_id()));
Assertions.assertThrows(EntityNotFoundException.class, () -> orderService.findOrder(order2.get_id()));
Assertions.assertEquals(orderService.findAllOrders().size(), 0);
}
@Test()
void testMaster() {
masterService.deleteAllMasters();
final Master customer = masterService.addMaster("Иван", "Иванов");
Assertions.assertNotNull(customer.get_id());
masterService.deleteAllMasters();
final Master customer1 = masterService.addMaster("Иван", "Иванов");
final Master findMaster = masterService.findMaster(customer1.get_id());
Assertions.assertEquals(customer1, findMaster);
masterService.deleteAllMasters();
Assertions.assertThrows(EntityNotFoundException.class, () -> masterService.findMaster(-1L));
masterService.deleteAllMasters();
masterService.addMaster("Иван", "Иванов");
masterService.addMaster("Петр", "Петров");
final List<Master> customers1 = masterService.findAllMasters();
Assertions.assertEquals(customers1.size(), 2);
masterService.deleteAllMasters();
final List<Master> customers2 = masterService.findAllMasters();
Assertions.assertEquals(customers2.size(), 0);
}
@Test
void testProduct() {
productService.deleteAllProducts();
final Product ticket1 = productService.addProduct("Руно", 100);
Assertions.assertNotNull(ticket1.get_id());
productService.deleteAllProducts();
final Product ticket2 = productService.addProduct("Шоколад", 100);
final Product findProduct = productService.findProduct(ticket2.get_id());
Assertions.assertEquals(ticket2, findProduct);
productService.deleteAllProducts();
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
productService.deleteAllProducts();
productService.addProduct("Автомобиль", 100);
productService.addProduct("Мячик", 100);
final List<Product> tickets1 = productService.findAllProducts();
Assertions.assertEquals(tickets1.size(), 2);
productService.deleteAllProducts();
final List<Product> tickets2 = productService.findAllProducts();
Assertions.assertEquals(tickets2.size(), 0);
}
@Test
void testCommand() {
productService.deleteAllProducts();
orderService.deleteAllOrders();
masterService.deleteAllMasters();
final Product product1 = productService.addProduct("Машинка", 300);
final Product product2 = productService.addProduct("Ключ", 200);
final Master master1 = masterService.addMaster("Кирилл", "Петрович");
final Master master2 = masterService.addMaster("Александр", "Камугович");
final MastersOrders order0 = orderService.addOrder(masterService.findMaster(master1.get_id()));
final MastersOrders order1 = orderService.addOrder(masterService.findMaster(master2.get_id()));
final MastersOrders order2 = orderService.addOrder(masterService.findMaster(master2.get_id()));
orderService.addProduct(order0.get_id(), product1);
orderService.addProduct(order1.get_id(), product1);
orderService.addProduct(order2.get_id(), product1);
Assertions.assertTrue(orderService.findOrdersWithProduct(master1.get_id(), product1).contains(order0));
Assertions.assertTrue(orderService.findOrdersWithProduct(master1.get_id(), product2).isEmpty());
Assertions.assertTrue(orderService.findOrdersWithProduct(master2.get_id(), product1).contains(order1)
&& orderService.findOrdersWithProduct(master2.get_id(), product1).contains(order2));
}
}

View File

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop