This commit is contained in:
Milana Ievlewa 2024-05-10 15:16:24 +04:00
parent bbbb903b2e
commit f2f313b4f8
33 changed files with 902 additions and 277 deletions

View File

@ -7,6 +7,17 @@ plugins {
group = 'com.example'
version = '0.0.1-SNAPSHOT'
defaultTasks 'bootRun'
jar {
enabled = false
}
bootJar {
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
}
assert System.properties['java.specification.version'] == '17' || '21'
java {
sourceCompatibility = '17'
}
@ -17,9 +28,13 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

BIN
data.mv.db Normal file

Binary file not shown.

153
data.trace.db Normal file
View File

@ -0,0 +1,153 @@
2024-05-10 15:01:13.422365+04:00 database: flush
org.h2.message.DbException: Внутренняя ошибка: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]"
General error: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]" [50000-224]
at org.h2.message.DbException.get(DbException.java:212)
at org.h2.message.DbException.convert(DbException.java:407)
at org.h2.mvstore.db.Store.lambda$new$0(Store.java:122)
at org.h2.mvstore.MVStore.handleException(MVStore.java:1546)
at org.h2.mvstore.MVStore.panic(MVStore.java:371)
at org.h2.mvstore.MVStore.<init>(MVStore.java:291)
at org.h2.mvstore.MVStore$Builder.open(MVStore.java:2035)
at org.h2.mvstore.db.Store.<init>(Store.java:133)
at org.h2.engine.Database.<init>(Database.java:326)
at org.h2.engine.Engine.openSession(Engine.java:92)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:343)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:125)
at org.h2.Driver.connect(Driver.java:59)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:100)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:428)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:61)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.getJdbcEnvironmentUsingJdbcMetadata(JdbcEnvironmentInitiator.java:276)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:107)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:130)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:238)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:215)
at org.hibernate.boot.model.relational.Database.<init>(Database.java:45)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.getDatabase(InFlightMetadataCollectorImpl.java:223)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:191)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:170)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1432)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1503)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:75)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1833)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1234)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:952)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:334)
at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46)
at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1454)
at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:553)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:225)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:152)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:163)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:378)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:383)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:378)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1708)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:377)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:290)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:289)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:279)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:278)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:757)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.h2.jdbc.JdbcSQLNonTransientException: Внутренняя ошибка: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]"
General error: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]" [50000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:566)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 138 more
Caused by: org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]
at org.h2.mvstore.DataUtils.newMVStoreException(DataUtils.java:996)
at org.h2.mvstore.SingleFileStore.lockFileChannel(SingleFileStore.java:143)
at org.h2.mvstore.SingleFileStore.open(SingleFileStore.java:117)
at org.h2.mvstore.SingleFileStore.open(SingleFileStore.java:81)
at org.h2.mvstore.MVStore.<init>(MVStore.java:286)
... 132 more

View File

@ -1,6 +1,6 @@
package com.example.demo;
import java.util.Objects;
import java.util.Arrays;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@ -41,23 +41,21 @@ public class DemoApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default categories values");
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
log.info("Create default types&dates values");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate _date = LocalDate.parse("2023-10-15", formatter);
final var type1 = typeService.create(new TypeEntity(null, "Концерт"));
final var type2 = typeService.create(new TypeEntity(null, "Кино"));
final var type3 = typeService.create(new TypeEntity(null, "Театр"));
final var type1 = typeService.create(new TypeEntity("Концерт"));
final var type2 = typeService.create(new TypeEntity("Кино"));
final var type3 = typeService.create(new TypeEntity("Театр"));
final var place1 = placeService.create(new PlaceEntity(null, "US, California"));
final var place2 = placeService.create(new PlaceEntity(null, "Germany, Berlin"));
final var place3 = placeService.create(new PlaceEntity(null, "UK, London"));
final var place1 = placeService.create(new PlaceEntity("US, California"));
final var place2 = placeService.create(new PlaceEntity("Germany, Berlin"));
final var place3 = placeService.create(new PlaceEntity("UK, London"));
log.info("Create default books values");
log.info("Create default ivents values");
iventService.create(new IventEntity(
null,
"Slipknot",
type1,
_date,
@ -65,10 +63,10 @@ public class DemoApplication implements CommandLineRunner {
"Участники группы Slipknot - это:<....>",
2500.33,
30,
place1));
place1,
""));
iventService.create(new IventEntity(
null,
"Placebo",
type1,
_date,
@ -76,10 +74,10 @@ public class DemoApplication implements CommandLineRunner {
"Группа Placebo состояла из следующих участников:<....>",
2500.33,
30,
place2));
place2,
""));
iventService.create(new IventEntity(
null,
"Radiohead",
type1,
_date,
@ -87,10 +85,10 @@ public class DemoApplication implements CommandLineRunner {
"Участниками Radiohead являются:<....>",
2500.33,
30,
place3));
place3,
""));
iventService.create(new IventEntity(
null,
"Сияние",
type2,
_date,
@ -98,10 +96,10 @@ public class DemoApplication implements CommandLineRunner {
"Актеры:<....>",
2500.33,
45,
place3));
place3,
""));
iventService.create(new IventEntity(
null,
"Мастер и Маргарита",
type3,
_date,
@ -109,12 +107,13 @@ public class DemoApplication implements CommandLineRunner {
"Автор: М. А. Булгаков",
2500.33,
30,
place2));
place2,
""));
log.info("Create default users values");
userService.create(new UserEntity(null, "Admin", "Admin@gmail.com", "admin"));
userService.create(new UserEntity(null, "Milana", "milana@gmail.com", "milana"));
userService.create(new UserEntity(null, "TestUser", "user@gmail.com", "test"));
userService.create(new UserEntity("Admin", "Admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test", "user"));
}
}
}

View File

@ -0,0 +1,97 @@
package com.example.demo.core.api;
import java.util.ArrayList;
import java.util.List;
public class PageDto<D> {
private List<D> items = new ArrayList<>();
private int itemsCount;
private int currentPage;
private int currentSize;
private int totalPages;
private long totalItems;
private boolean isFirst;
private boolean isLast;
private boolean hasNext;
private boolean hasPrevious;
public List<D> getItems() {
return items;
}
public void setItems(List<D> items) {
this.items = items;
}
public int getItemsCount() {
return itemsCount;
}
public void setItemsCount(int itemsCount) {
this.itemsCount = itemsCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getCurrentSize() {
return currentSize;
}
public void setCurrentSize(int currentSize) {
this.currentSize = currentSize;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public long getTotalItems() {
return totalItems;
}
public void setTotalItems(long totalItems) {
this.totalItems = totalItems;
}
public boolean isFirst() {
return isFirst;
}
public void setFirst(boolean isFirst) {
this.isFirst = isFirst;
}
public boolean isLast() {
return isLast;
}
public void setLast(boolean isLast) {
this.isLast = isLast;
}
public boolean isHasNext() {
return hasNext;
}
public void setHasNext(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean isHasPrevious() {
return hasPrevious;
}
public void setHasPrevious(boolean hasPrevious) {
this.hasPrevious = hasPrevious;
}
}

View File

@ -0,0 +1,25 @@
package com.example.demo.core.api;
import java.util.function.Function;
import org.springframework.data.domain.Page;
public class PageDtoMapper {
private PageDtoMapper() {
}
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
final PageDto<D> dto = new PageDto<>();
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
dto.setItemsCount(page.getNumberOfElements());
dto.setCurrentPage(page.getNumber());
dto.setCurrentSize(page.getSize());
dto.setTotalPages(page.getTotalPages());
dto.setTotalItems(page.getTotalElements());
dto.setFirst(page.isFirst());
dto.setLast(page.isLast());
dto.setHasNext(page.hasNext());
dto.setHasPrevious(page.hasPrevious());
return dto;
}
}

View File

@ -1,7 +1,9 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0";
public static final String DEFAULT_PAGE_SIZE = "5";
private Constants() {
}

View File

@ -9,8 +9,6 @@ import org.springframework.context.annotation.Configuration;
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
return new ModelMapper();
}
}

View File

@ -1,7 +1,7 @@
package com.example.demo.core.error;
public class NotFoundException extends RuntimeException {
public NotFoundException(Long id) {
super(String.format("Entity with id [%s] is not found or not exists", id));
public <T> NotFoundException(Class<T> clazz, Long id) {
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
}
}

View File

@ -1,6 +1,18 @@
package com.example.demo.core.model;
import com.example.demo.core.configuration.Constants;
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, generator = Constants.SEQUENCE_NAME)
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
protected Long id;
protected BaseEntity() {

View File

@ -3,7 +3,7 @@ package com.example.demo.ivents.api;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Optional;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;

View File

@ -8,6 +8,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class IventDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String itName;
@ -30,7 +31,6 @@ public class IventDto {
@Min(1)
private Long placeId;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}

View File

@ -2,28 +2,44 @@ package com.example.demo.ivents.model;
import java.util.Objects;
import java.time.LocalDate;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.places.model.PlaceEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "ivents")
public class IventEntity extends BaseEntity {
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type;
@Column(nullable = false)
private LocalDate date;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private String other;
@Column(nullable = false)
private Double price;
@Column(nullable = false)
private Integer count;
@ManyToOne
@JoinColumn(name = "placeId", nullable = false)
private PlaceEntity place;
private String image;
public IventEntity() {
super();
}
public IventEntity(Long id, String name, TypeEntity type, LocalDate date,
String description, String other, Double price, Integer count, PlaceEntity place) {
super(id);
public IventEntity(String name, TypeEntity type, LocalDate date,
String description, String other, Double price, Integer count, PlaceEntity place, String image) {
this.name = name;
this.type = type;
this.date = date;
@ -32,6 +48,7 @@ public class IventEntity extends BaseEntity {
this.price = price;
this.count = count;
this.place = place;
this.image = image;
}
public String getName() {
@ -98,9 +115,17 @@ public class IventEntity extends BaseEntity {
this.place = place;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public int hashCode() {
return Objects.hash(id, name, type, date, description, other, price, count, place);
return Objects.hash(id, name, type, date, description, other, price, count, place, image);
}
@Override
@ -118,7 +143,8 @@ public class IventEntity extends BaseEntity {
&& Objects.equals(otheren.getOther(), other)
&& Objects.equals(otheren.getPrice(), price)
&& Objects.equals(otheren.getCount(), count)
&& Objects.equals(otheren.getPlace(), place);
&& Objects.equals(otheren.getPlace(), place)
&& Objects.equals(otheren.getImage(), image);
}
}

View File

@ -1,11 +1,26 @@
package com.example.demo.ivents.repository;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
@Repository
public class IventRepository extends MapRepository<IventEntity> {
}
public interface IventRepository extends CrudRepository<IventEntity, Long> , PagingAndSortingRepository<IventEntity, Long> {
List<IventEntity> findByTypeId(Long typeId);
List<IventEntity> findByPlaceId(Long placeId);
List<IventEntity> findByTypeIdAndPlaceId(Long typeId, Long placeId);
List<IventEntity> findAllByDateBetween(LocalDate startDate, LocalDate endDate);
Page<IventEntity> findByTypeId(Long typeId, Pageable pageable);
Page<IventEntity> findByPlaceId(Long placeId, Pageable pageable);
Page<IventEntity> findByTypeIdAndPlaceId(Long typeId, Long placeId, Pageable pageable);
Page<IventEntity> findAllByDateBetween(LocalDate startDate, LocalDate endDate, Pageable pageable);
}

View File

@ -1,76 +1,118 @@
package com.example.demo.ivents.service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.repository.IventRepository;
import com.example.demo.types.repository.TypeRepository;
import com.example.demo.places.repository.PlaceRepository;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
@Service
public class IventService {
private final TypeRepository typeRepository;
private final PlaceRepository placeRepository;
private final IventRepository repository;
public IventService(IventRepository repository) {
public IventService(TypeRepository typeRepository, PlaceRepository placeRepository, IventRepository repository) {
this.repository = repository;
this.typeRepository = typeRepository;
this.placeRepository = placeRepository;
}
@Transactional
public List<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate) {
List<IventEntity> result = repository.getAll();
List<IventEntity> result;
if (startDate != null || endDate != null) {
LocalDate start = Objects.requireNonNullElse(startDate, LocalDate.MIN);
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now());
result = result.stream()
.filter(item -> (startDate == null || item.getDate().isAfter(start.minusDays(1)))
&& (endDate == null || item.getDate().isBefore(end.plusDays(1)))
)
.collect(Collectors.toList());
if (startDate != null && endDate != null) {
result = StreamSupport.stream(repository.findAllByDateBetween(startDate, endDate).spliterator(), false).toList();
} else if (startDate != null) {
result = StreamSupport.stream(repository.findAllByDateBetween(startDate, LocalDate.now()).spliterator(), false).toList();
} else {
result = StreamSupport.stream(repository.findAllByDateBetween(LocalDate.MIN, endDate).spliterator(), false).toList();
}
} else {
result = StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
if (!Objects.equals(typeId, 0L)){
result = result.stream()
.filter(item -> item.getType().getId().equals(typeId))
.toList();
if (typeId != null && typeId != 0L) {
if (placeId != null && placeId != 0L) {
result.retainAll(repository.findByTypeIdAndPlaceId(typeId, placeId));
} else {
result.retainAll(repository.findByTypeId(typeId));
}
}
if (!Objects.equals(placeId, 0L)){
result = result.stream()
.filter(item -> item.getPlace().getId().equals(placeId))
.toList();
if (placeId != null && placeId != 0L) {
if (typeId == null || typeId == 0L) {
result.retainAll(repository.findByPlaceId(placeId));
}
}
return result;
}
public List<IventEntity> getAllDate(LocalDate startDate, LocalDate endDate) {
if (startDate == null) {
throw new IllegalArgumentException("Дата 'от' должна быть указана");
@Transactional
public Page<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate, Pageable pageable) {
Page<IventEntity> resultPage;
if (startDate != null || endDate != null) {
if (startDate != null && endDate != null) {
resultPage = repository.findAllByDateBetween(startDate, endDate, pageable);
} else if (startDate != null) {
resultPage = repository.findAllByDateBetween(startDate, LocalDate.now(), pageable);
} else {
resultPage = repository.findAllByDateBetween(LocalDate.MIN, endDate, pageable);
}
} else {
resultPage = repository.findAll(pageable);
}
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now());
return repository.getAll().stream()
.filter(item -> item.getDate().isAfter(startDate.minusDays(1)) && item.getDate().isBefore(end.plusDays(1))) // использование методов isAfter и isBefore для LocalDate
.collect(Collectors.toList());
if (typeId != null && typeId != 0L) {
if (placeId != null && placeId != 0L) {
resultPage = repository.findByTypeIdAndPlaceId(typeId, placeId, pageable);
} else {
resultPage = repository.findByTypeId(typeId, pageable);
}
}
if (placeId != null && placeId != 0L) {
if (typeId == null || typeId == 0L) {
resultPage = repository.findByPlaceId(placeId, pageable);
}
}
return resultPage;
}
public List<IventEntity> getAll() {
return repository.getAll();
}
@Transactional(readOnly = true)
public IventEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(IventEntity.class, id));
}
@Transactional
public IventEntity create(IventEntity entity) {
return repository.create(entity);
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public IventEntity update(Long id, IventEntity entity) {
final IventEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
@ -81,11 +123,23 @@ public class IventService {
existsEntity.setPrice(entity.getPrice());
existsEntity.setCount(entity.getCount());
existsEntity.setPlace(entity.getPlace());
return repository.update(existsEntity);
existsEntity.setImage(entity.getImage());
return repository.save(existsEntity);
}
@Transactional
public IventEntity delete(Long id) {
final IventEntity existsEntity = get(id);
return repository.delete(existsEntity);
repository.delete(existsEntity);
return existsEntity;
}
/*public List<IventEntity> getAllDate(LocalDate startDate, LocalDate endDate) {
if (startDate == null) {
throw new IllegalArgumentException("Дата 'от' должна быть указана");
}
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now());
return repository.getAll().stream()
.filter(item -> item.getDate().isAfter(startDate.minusDays(1)) && item.getDate().isBefore(end.plusDays(1))) // использование методов isAfter и isBefore для LocalDate
.collect(Collectors.toList());
}*/
}

View File

@ -5,11 +5,11 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class PlaceDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}

View File

@ -4,15 +4,20 @@ import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "places")
public class PlaceEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
public PlaceEntity() {
super();
}
public PlaceEntity(Long id, String name) {
super(id);
public PlaceEntity(String name) {
this.name = name;
}

View File

@ -1,11 +1,11 @@
package com.example.demo.places.repository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import com.example.demo.core.repository.MapRepository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.places.model.PlaceEntity;
@Repository
public class PlaceRepository extends MapRepository<PlaceEntity> {
public interface PlaceRepository extends CrudRepository<PlaceEntity, Long> {
Optional<PlaceEntity> findByNameIgnoreCase(String name);
}

View File

@ -1,9 +1,10 @@
package com.example.demo.places.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.places.model.PlaceEntity;
@ -17,28 +18,45 @@ public class PlaceService {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Place with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<PlaceEntity> getAll() {
return repository.getAll();
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public PlaceEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(PlaceEntity.class, id));
}
@Transactional
public PlaceEntity create(PlaceEntity entity) {
return repository.create(entity);
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public PlaceEntity update(Long id, PlaceEntity entity) {
final PlaceEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
return repository.update(existsEntity);
return repository.save(existsEntity);
}
@Transactional
public PlaceEntity delete(Long id) {
final PlaceEntity existsEntity = get(id);
return repository.delete(existsEntity);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -5,11 +5,11 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}

View File

@ -4,15 +4,20 @@ import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "types")
public class TypeEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
public TypeEntity() {
super();
}
public TypeEntity(Long id, String name) {
super(id);
public TypeEntity(String name) {
this.name = name;
}

View File

@ -1,11 +1,11 @@
package com.example.demo.types.repository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import com.example.demo.core.repository.MapRepository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.types.model.TypeEntity;
@Repository
public class TypeRepository extends MapRepository<TypeEntity> {
public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
Optional<TypeEntity> findByNameIgnoreCase(String name);
}

View File

@ -1,9 +1,10 @@
package com.example.demo.types.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.types.model.TypeEntity;
@ -17,28 +18,45 @@ public class TypeService {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<TypeEntity> getAll() {
return repository.getAll();
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public TypeEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(TypeEntity.class, id));
}
@Transactional
public TypeEntity create(TypeEntity entity) {
return repository.create(entity);
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public TypeEntity update(Long id, TypeEntity entity) {
final TypeEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
return repository.update(existsEntity);
return repository.save(existsEntity);
}
@Transactional
public TypeEntity delete(Long id) {
final TypeEntity existsEntity = get(id);
return repository.delete(existsEntity);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -1,7 +1,5 @@
package com.example.demo.users.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
@ -10,8 +8,11 @@ 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 com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@ -38,8 +39,10 @@ public class UserController {
}
@GetMapping
public List<UserDto> getAll() {
return userService.getAll().stream().map(this::toDto).toList();
public PageDto<UserDto> getAll(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
}
@GetMapping("/{id}")
@ -53,7 +56,7 @@ public class UserController {
}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid UserDto dto) {
return toDto(userService.update(id, toEntity(dto)));
}

View File

@ -3,8 +3,10 @@ package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String handle;
@ -12,8 +14,10 @@ public class UserDto {
private String email;
@NotBlank
private String password;
@NotBlank
@Size(min = 1, max = 20)
private String accessLevel;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
@ -45,5 +49,13 @@ public class UserDto {
public void setPassword(String password) {
this.password = password;
}
public String getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
}
}

View File

@ -4,20 +4,33 @@ import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String handle;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String accessLevel;
public UserEntity() {
super();
}
public UserEntity(Long id, String handle, String email, String password) {
super(id);
public UserEntity(String handle, String email, String password, String accessLevel) {
this.handle = handle;
this.email = email;
this.password = password;
this.accessLevel = accessLevel;
}
public String getHandle() {
@ -44,9 +57,17 @@ public class UserEntity extends BaseEntity {
this.password = password;
}
public String getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
}
@Override
public int hashCode() {
return Objects.hash(id, handle, email, password);
return Objects.hash(id, handle, email, password, accessLevel);
}
@Override
@ -59,7 +80,8 @@ public class UserEntity extends BaseEntity {
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getHandle(), handle)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password);
&& Objects.equals(other.getPassword(), password)
&& Objects.equals(other.getAccessLevel(), accessLevel);
}
}

View File

@ -1,11 +1,14 @@
package com.example.demo.users.repository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.users.model.UserEntity;
@Repository
public class UserRepository extends MapRepository<UserEntity> {
public interface UserRepository
extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
Optional<UserEntity> findByHandleIgnoreCase(String handle);
}

View File

@ -1,9 +1,12 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
@ -17,28 +20,54 @@ public class UserService {
this.repository = repository;
}
private void checkHandle(String handle) {
if (repository.findByHandleIgnoreCase(handle).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", handle));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return repository.getAll();
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
public UserEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
@Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size));
}
@Transactional(readOnly = true)
public UserEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public UserEntity create(UserEntity entity) {
return repository.create(entity);
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkHandle(entity.getHandle());
return repository.save(entity);
}
public UserEntity update(Long id, UserEntity entity) {
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
existsEntity.setHandle(entity.getHandle());
return repository.update(existsEntity);
existsEntity.setEmail(entity.getEmail());
existsEntity.setPassword(entity.getPassword());
existsEntity.setAccessLevel(entity.getAccessLevel());
repository.save(existsEntity);
return existsEntity;
}
public UserEntity delete(Long id) {
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
return repository.delete(existsEntity);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -1,2 +1,20 @@
spring.application.name=demo
server.port=8081
# Server
spring.main.banner-mode=off
server.port=8081
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.open-in-view=false
# spring.jpa.show-sql=true
# spring.jpa.properties.hibernate.format_sql=true
# H2 console
spring.h2.console.enabled=true

View File

@ -2,14 +2,19 @@ package com.example.demo;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
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.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
@ -19,6 +24,8 @@ import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.core.error.NotFoundException;
import jakarta.persistence.EntityManager;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class IventServiceTests {
@ -31,53 +38,73 @@ class IventServiceTests {
@Autowired
private IventService iventService;
private IventEntity ivent;
@BeforeEach
void createData() {
removeData();
final var type = typeService.create(new TypeEntity("Концерт"));
final var place = placeService.create(new PlaceEntity("USA, California"));
ivent = iventService.create(new IventEntity(
"Slipknot",
type,
LocalDate.of(2023, 10, 15),
"Описание Slipknot",
"Участники группы Slipknot",
2500.33,
30,
place,
""));
iventService.create(new IventEntity(
"Placebo",
type,
LocalDate.of(2024, 2, 13),
"Описание Placebo",
"Группа Placebo",
2500.33,
30,
place,
""));
iventService.create(new IventEntity(
"Radiohead",
type,
LocalDate.of(2024, 2, 15),
"Описание Radiohead",
"Участники Radiohead",
2500.33,
30,
place,
""));
}
@AfterEach
void removeData() {
iventService.getAll(0L, 0L, null, null).forEach(item -> iventService.delete(item.getId()));
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
placeService.getAll().forEach(item -> placeService.delete(item.getId()));
}
@Transactional
@Test
@Order(1)
void createTest() {
Assertions.assertEquals(3, iventService.getAll(0L, 0L, null, null).size());
Assertions.assertEquals(ivent, iventService.get(ivent.getId()));
}
@Test
@Order(2)
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> iventService.get(0L));
}
@Test
@Order(1)
void createTest() {
final TypeEntity type = typeService.create(new TypeEntity(null, "Концерт"));
final PlaceEntity place = placeService.create(new PlaceEntity(null, "USA, California"));
iventService.create(new IventEntity(
null,
"Slipknot",
type,
LocalDate.of(2023, 10, 15),
"Slipknot - американская ню-метал группа, основанная в 1995 году. Они известны своим агрессивным звучанием, смешением хардкор-панк и тяжелого метала с индастриалом и элементами альтернативного рока.",
"Участники группы Slipknot - это:<....>",
2500.33,
30,
place));
iventService.create(new IventEntity(
null,
"Placebo",
type,
LocalDate.of(2024, 2, 13),
"Placebo - британская альтернативная рок-группа, основанная в 1994 году. Они известны своим уникальным звучанием, погружающим слушателей в меланхоличную атмосферу и наполняющим музыку эмоциональным содержанием.",
"Группа Placebo состояла из следующих участников:<....>",
2500.33,
30,
place));
final IventEntity last = iventService.create(new IventEntity(
null,
"Radiohead",
type,
LocalDate.of(2024, 2, 15),
"Radiohead - британская рок-группа, образованная в 1985 году.",
"Участниками Radiohead являются:<....>",
2500.33,
30,
place));
Assertions.assertEquals(3, iventService.getAll().size());
Assertions.assertEquals(last, iventService.get(3L));
}
@Test
@Order(2)
@Order(3)
void sortDates() {
LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate end = LocalDate.of(2024, 5, 15);
@ -88,17 +115,34 @@ class IventServiceTests {
}
@Test
@Order(3)
void updateTest() {
final TypeEntity type = typeService.create(new TypeEntity(null, "Кино"));
final PlaceEntity place = placeService.create(new PlaceEntity(null, "Germany, Berlin"));
final String test = "TEST";
final IventEntity entity = iventService.get(3L);
final TypeEntity oldType = entity.getType();
final PlaceEntity oldPlace = entity.getPlace();
final String oldName = entity.getName();
final IventEntity newEntity = iventService.update(3L, new IventEntity(
@Order(4)
void createNullableTest() {
final IventEntity nullIvent = new IventEntity(
null,
null,
null,
null,
null ,
null,
null,
null,
"");
Assertions.assertThrows(DataIntegrityViolationException.class, () -> iventService.create(nullIvent));
}
@Transactional
@Test
@Order(5)
void updateTest() {
final String test = "TEST";
final TypeEntity type = typeService.create(new TypeEntity("Кино"));
final PlaceEntity place = placeService.create(new PlaceEntity("Germany, Berlin"));
final String oldName = ivent.getName();
final TypeEntity oldType = ivent.getType();
final PlaceEntity oldPlace = ivent.getPlace();
final IventEntity newEntity = iventService.update(ivent.getId(), new IventEntity(
test,
type,
LocalDate.of(2023, 10, 15),
@ -106,9 +150,10 @@ class IventServiceTests {
"Участниками Radiohead являются:<....>",
2500.33,
30,
place));
Assertions.assertEquals(3, iventService.getAll().size());
Assertions.assertEquals(newEntity, iventService.get(3L));
place,
""));
Assertions.assertEquals(3, iventService.getAll(0L, 0L, null, null).size());
Assertions.assertEquals(newEntity, iventService.get(ivent.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertEquals(type, newEntity.getType());
Assertions.assertEquals(place, newEntity.getPlace());
@ -118,26 +163,16 @@ class IventServiceTests {
}
@Test
@Order(4)
@Order(6)
void deleteTest() {
iventService.delete(3L);
Assertions.assertEquals(2, iventService.getAll().size());
final IventEntity last = iventService.get(2L);
Assertions.assertEquals(2L, last.getId());
iventService.delete(ivent.getId());
Assertions.assertEquals(2, iventService.getAll(0L, 0L, null, null).size());
final TypeEntity type = typeService.create(new TypeEntity(null, "Концерт"));
final PlaceEntity place = placeService.create(new PlaceEntity(null, "USA, California"));
final IventEntity newEntity = iventService.create(new IventEntity(
null,
"Deftones",
type,
LocalDate.of(2023, 10, 15),
"Deftones - американская альтернативная метал-группа, сформированная в 1988 году. ",
"Участники Deftones:<....>",
2550.33,
25,
place));
Assertions.assertEquals(3, iventService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
final IventEntity newEntity = iventService.create(new IventEntity(ivent.getName(), ivent.getType(),
ivent.getDate(), ivent.getDesc(), ivent.getOther(), ivent.getPrice(), ivent.getCount(),
ivent.getPlace(), ivent.getImage()));
Assertions.assertEquals(1, typeService.getAll().size());
Assertions.assertEquals(1, placeService.getAll().size());
Assertions.assertNotEquals(ivent.getId(), newEntity.getId());
}
}

View File

@ -1,22 +1,38 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.BeforeEach;
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.dao.DataIntegrityViolationException;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class PlaceServiceTests {
@Autowired
private PlaceService placeService;
private PlaceEntity place;
@BeforeEach
void createData() {
removeData();
place = placeService.create(new PlaceEntity("USA, California"));
placeService.create(new PlaceEntity("Germany, Berlin"));
placeService.create(new PlaceEntity("UK, London"));
}
@AfterEach
void removeData() {
placeService.getAll().forEach(item -> placeService.delete(item.getId()));
}
@Test
void getTest() {
@ -24,39 +40,42 @@ class PlaceServiceTests {
}
@Test
@Order(1)
void createTest() {
placeService.create(new PlaceEntity(null, "USA, California"));
placeService.create(new PlaceEntity(null, "Germany, Berlin"));
final PlaceEntity last = placeService.create(new PlaceEntity(null, "UK, London"));
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertEquals(last, placeService.get(3L));
Assertions.assertEquals(place, placeService.get(place.getId()));
}
@Test
@Order(2)
void createNotUniqueTest() {
final PlaceEntity nonUniquePlace = new PlaceEntity("USA, California");
Assertions.assertThrows(IllegalArgumentException.class, () -> placeService.create(nonUniquePlace));
}
@Test
void createNullableTest() {
final PlaceEntity nullablePlace= new PlaceEntity(null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> placeService.create(nullablePlace));
}
@Test
void updateTest() {
final String test = "TEST";
final PlaceEntity entity = placeService.get(3L);
final String oldName = entity.getName();
final PlaceEntity newEntity = placeService.update(3L, new PlaceEntity(1L, test));
final String oldName = place.getName();
final PlaceEntity newEntity = placeService.update(place.getId(), new PlaceEntity(test));
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertEquals(newEntity, placeService.get(3L));
Assertions.assertEquals(newEntity, placeService.get(place.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
}
@Test
@Order(3)
void deleteTest() {
placeService.delete(3L);
Assertions.assertEquals(2, placeService.getAll().size());
final PlaceEntity last = placeService.get(2L);
Assertions.assertEquals(2L, last.getId());
placeService.delete(place.getId());
Assertions.assertEquals(2, placeService.getAll().size());
final PlaceEntity newEntity = placeService.create(new PlaceEntity(null, "UK, London"));
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
final PlaceEntity newEntity = placeService.create(new PlaceEntity(place.getName()));
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertNotEquals(place.getId(), newEntity.getId());
}
}

View File

@ -1,22 +1,37 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.BeforeEach;
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.dao.DataIntegrityViolationException;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class TypeServiceTests {
@Autowired
private TypeService typeService;
private TypeEntity type;
@BeforeEach
void createData() {
removeData();
type = typeService.create(new TypeEntity("USA, California"));
typeService.create(new TypeEntity("Germany, Berlin"));
typeService.create(new TypeEntity("UK, London"));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
}
@Test
void getTest() {
@ -24,38 +39,41 @@ class TypeServiceTests {
}
@Test
@Order(1)
void createTest() {
typeService.create(new TypeEntity(null, "Кино"));
typeService.create(new TypeEntity(null, "Концерт"));
final TypeEntity last = typeService.create(new TypeEntity(null, "Театр"));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(last, typeService.get(3L));
Assertions.assertEquals(type, typeService.get(type.getId()));
}
@Test
@Order(2)
void createNotUniqueTest() {
final TypeEntity nonUniqueType = new TypeEntity("USA, California");
Assertions.assertThrows(IllegalArgumentException.class, () -> typeService.create(nonUniqueType));
}
@Test
void createNullableTest() {
final TypeEntity nullableType= new TypeEntity(null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
}
@Test
void updateTest() {
final String test = "TEST";
final TypeEntity entity = typeService.get(3L);
final String oldName = entity.getName();
final TypeEntity newEntity = typeService.update(3L, new TypeEntity(1L, test));
final String oldName = type.getName();
final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(newEntity, typeService.get(3L));
Assertions.assertEquals(newEntity, typeService.get(type.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
}
@Test
@Order(3)
void deleteTest() {
typeService.delete(3L);
Assertions.assertEquals(2, typeService.getAll().size());
final TypeEntity last = typeService.get(2L);
Assertions.assertEquals(2L, last.getId());
typeService.delete(type.getId());
Assertions.assertEquals(2, typeService.getAll().size());
final TypeEntity newEntity = typeService.create(new TypeEntity(null, "Театр"));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName()));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertNotEquals(type.getId(), newEntity.getId());
}
}
}

View File

@ -1,62 +1,86 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.BeforeEach;
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.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserServiceTests {
@Autowired
private UserService userService;
private UserEntity user;
@BeforeEach
void createData() {
removeData();
user = userService.create(new UserEntity("Admin", "admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test", "user"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Transactional
@Test
@Order(1)
void createTest() {
userService.create(new UserEntity(null, "Admin", "admin@gmail.com", "admin"));
userService.create(new UserEntity(null, "Milana", "milana@gmail.com", "milana"));
final UserEntity last = userService.create(new UserEntity(null, "TestUser", "user@gmail.com", "test"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(last, userService.get(3L));
Assertions.assertEquals(user, userService.get(user.getId()));
}
@Test
@Order(2)
void createNotUniqueTest() {
final UserEntity nonUniqueUser = new UserEntity("Milana", "milana@gmail.com", "milana", "user");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueUser));
}
@Test
void createNullableTest() {
final UserEntity nullableUser = new UserEntity(null, "email@gamil.com", "pass", "admin");
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableUser));
}
@Transactional
@Test
void updateTest() {
final String test = "TEST";
final UserEntity entity = userService.get(3L);
final String oldName = entity.getHandle();
final UserEntity newEntity = userService.update(3L, new UserEntity(1L, test, "user@gmail.com", "test"));
final String oldLogin = user.getHandle();
final UserEntity newEntity = userService.update(user.getId(),
new UserEntity(test, "admin@gmail.com", "admin", "admin"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(3L));
Assertions.assertEquals(newEntity, userService.get(user.getId()));
Assertions.assertEquals(test, newEntity.getHandle());
Assertions.assertNotEquals(oldName, newEntity.getHandle());
Assertions.assertNotEquals(oldLogin, newEntity.getHandle());
}
@Test
@Order(3)
void deleteTest() {
userService.delete(3L);
userService.delete(user.getId());
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity last = userService.get(2L);
Assertions.assertEquals(2L, last.getId());
final UserEntity newEntity = userService.create(new UserEntity(null, "TestUser", "user@gmail.com", "test"));
final UserEntity newEntity = userService
.create(new UserEntity("Admin", "admin@gmail.com", "admin", "admin"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
Assertions.assertNotEquals(user.getId(), newEntity.getId());
}
}