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' group = 'com.example'
version = '0.0.1-SNAPSHOT' 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 { java {
sourceCompatibility = '17' sourceCompatibility = '17'
} }
@ -17,9 +28,13 @@ repositories {
dependencies { dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' 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.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.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' 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; package com.example.demo;
import java.util.Objects; import java.util.Arrays;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@ -41,23 +41,21 @@ public class DemoApplication implements CommandLineRunner {
@Override @Override
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
if (args.length > 0 && Objects.equals("--populate", args[0])) { log.info("Create default types&dates values");
log.info("Create default categories values");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate _date = LocalDate.parse("2023-10-15", formatter); LocalDate _date = LocalDate.parse("2023-10-15", formatter);
final var type1 = typeService.create(new TypeEntity(null, "Концерт")); final var type1 = typeService.create(new TypeEntity("Концерт"));
final var type2 = typeService.create(new TypeEntity(null, "Кино")); final var type2 = typeService.create(new TypeEntity("Кино"));
final var type3 = typeService.create(new TypeEntity(null, "Театр")); final var type3 = typeService.create(new TypeEntity("Театр"));
final var place1 = placeService.create(new PlaceEntity(null, "US, California")); final var place1 = placeService.create(new PlaceEntity("US, California"));
final var place2 = placeService.create(new PlaceEntity(null, "Germany, Berlin")); final var place2 = placeService.create(new PlaceEntity("Germany, Berlin"));
final var place3 = placeService.create(new PlaceEntity(null, "UK, London")); 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( iventService.create(new IventEntity(
null,
"Slipknot", "Slipknot",
type1, type1,
_date, _date,
@ -65,10 +63,10 @@ public class DemoApplication implements CommandLineRunner {
"Участники группы Slipknot - это:<....>", "Участники группы Slipknot - это:<....>",
2500.33, 2500.33,
30, 30,
place1)); place1,
""));
iventService.create(new IventEntity( iventService.create(new IventEntity(
null,
"Placebo", "Placebo",
type1, type1,
_date, _date,
@ -76,10 +74,10 @@ public class DemoApplication implements CommandLineRunner {
"Группа Placebo состояла из следующих участников:<....>", "Группа Placebo состояла из следующих участников:<....>",
2500.33, 2500.33,
30, 30,
place2)); place2,
""));
iventService.create(new IventEntity( iventService.create(new IventEntity(
null,
"Radiohead", "Radiohead",
type1, type1,
_date, _date,
@ -87,10 +85,10 @@ public class DemoApplication implements CommandLineRunner {
"Участниками Radiohead являются:<....>", "Участниками Radiohead являются:<....>",
2500.33, 2500.33,
30, 30,
place3)); place3,
""));
iventService.create(new IventEntity( iventService.create(new IventEntity(
null,
"Сияние", "Сияние",
type2, type2,
_date, _date,
@ -98,10 +96,10 @@ public class DemoApplication implements CommandLineRunner {
"Актеры:<....>", "Актеры:<....>",
2500.33, 2500.33,
45, 45,
place3)); place3,
""));
iventService.create(new IventEntity( iventService.create(new IventEntity(
null,
"Мастер и Маргарита", "Мастер и Маргарита",
type3, type3,
_date, _date,
@ -109,12 +107,13 @@ public class DemoApplication implements CommandLineRunner {
"Автор: М. А. Булгаков", "Автор: М. А. Булгаков",
2500.33, 2500.33,
30, 30,
place2)); place2,
""));
log.info("Create default users values"); log.info("Create default users values");
userService.create(new UserEntity(null, "Admin", "Admin@gmail.com", "admin")); userService.create(new UserEntity("Admin", "Admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity(null, "Milana", "milana@gmail.com", "milana")); userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity(null, "TestUser", "user@gmail.com", "test")); 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; package com.example.demo.core.configuration;
public class Constants { public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0"; public static final String API_URL = "/api/1.0";
public static final String DEFAULT_PAGE_SIZE = "5";
private Constants() { private Constants() {
} }

View File

@ -10,7 +10,5 @@ public class MapperConfiguration {
@Bean @Bean
ModelMapper modelMapper() { ModelMapper modelMapper() {
return new ModelMapper(); return new ModelMapper();
} }
} }

View File

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

View File

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

View File

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

View File

@ -2,28 +2,44 @@ package com.example.demo.ivents.model;
import java.util.Objects; import java.util.Objects;
import java.time.LocalDate; import java.time.LocalDate;
import com.example.demo.core.model.BaseEntity; import com.example.demo.core.model.BaseEntity;
import com.example.demo.types.model.TypeEntity; import com.example.demo.types.model.TypeEntity;
import com.example.demo.places.model.PlaceEntity; 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 { public class IventEntity extends BaseEntity {
@Column(nullable = false)
private String name; private String name;
@ManyToOne
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type; private TypeEntity type;
@Column(nullable = false)
private LocalDate date; private LocalDate date;
@Column(nullable = false)
private String description; private String description;
@Column(nullable = false)
private String other; private String other;
@Column(nullable = false)
private Double price; private Double price;
@Column(nullable = false)
private Integer count; private Integer count;
@ManyToOne
@JoinColumn(name = "placeId", nullable = false)
private PlaceEntity place; private PlaceEntity place;
private String image;
public IventEntity() { public IventEntity() {
super();
} }
public IventEntity(Long id, String name, TypeEntity type, LocalDate date, public IventEntity(String name, TypeEntity type, LocalDate date,
String description, String other, Double price, Integer count, PlaceEntity place) { String description, String other, Double price, Integer count, PlaceEntity place, String image) {
super(id);
this.name = name; this.name = name;
this.type = type; this.type = type;
this.date = date; this.date = date;
@ -32,6 +48,7 @@ public class IventEntity extends BaseEntity {
this.price = price; this.price = price;
this.count = count; this.count = count;
this.place = place; this.place = place;
this.image = image;
} }
public String getName() { public String getName() {
@ -98,9 +115,17 @@ public class IventEntity extends BaseEntity {
this.place = place; this.place = place;
} }
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override @Override
public int hashCode() { 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 @Override
@ -118,7 +143,8 @@ public class IventEntity extends BaseEntity {
&& Objects.equals(otheren.getOther(), other) && Objects.equals(otheren.getOther(), other)
&& Objects.equals(otheren.getPrice(), price) && Objects.equals(otheren.getPrice(), price)
&& Objects.equals(otheren.getCount(), count) && 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; 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.ivents.model.IventEntity;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
@Repository public interface IventRepository extends CrudRepository<IventEntity, Long> , PagingAndSortingRepository<IventEntity, Long> {
public class IventRepository extends MapRepository<IventEntity> { 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; package com.example.demo.ivents.service;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; 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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.ivents.model.IventEntity; import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.repository.IventRepository; 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 @Service
public class IventService { public class IventService {
private final TypeRepository typeRepository;
private final PlaceRepository placeRepository;
private final IventRepository repository; private final IventRepository repository;
public IventService(IventRepository repository) { public IventService(TypeRepository typeRepository, PlaceRepository placeRepository, IventRepository repository) {
this.repository = repository; this.repository = repository;
this.typeRepository = typeRepository;
this.placeRepository = placeRepository;
} }
@Transactional
public List<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate) { 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) { if (startDate != null || endDate != null) {
LocalDate start = Objects.requireNonNullElse(startDate, LocalDate.MIN); if (startDate != null && endDate != null) {
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now()); result = StreamSupport.stream(repository.findAllByDateBetween(startDate, endDate).spliterator(), false).toList();
} else if (startDate != null) {
result = result.stream() result = StreamSupport.stream(repository.findAllByDateBetween(startDate, LocalDate.now()).spliterator(), false).toList();
.filter(item -> (startDate == null || item.getDate().isAfter(start.minusDays(1))) } else {
&& (endDate == null || item.getDate().isBefore(end.plusDays(1))) result = StreamSupport.stream(repository.findAllByDateBetween(LocalDate.MIN, endDate).spliterator(), false).toList();
) }
.collect(Collectors.toList()); } else {
result = StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
if (!Objects.equals(typeId, 0L)){ if (typeId != null && typeId != 0L) {
result = result.stream() if (placeId != null && placeId != 0L) {
.filter(item -> item.getType().getId().equals(typeId)) result.retainAll(repository.findByTypeIdAndPlaceId(typeId, placeId));
.toList(); } else {
result.retainAll(repository.findByTypeId(typeId));
}
} }
if (!Objects.equals(placeId, 0L)){ if (placeId != null && placeId != 0L) {
result = result.stream() if (typeId == null || typeId == 0L) {
.filter(item -> item.getPlace().getId().equals(placeId)) result.retainAll(repository.findByPlaceId(placeId));
.toList();
} }
}
return result; return result;
} }
public List<IventEntity> getAllDate(LocalDate startDate, LocalDate endDate) { @Transactional
if (startDate == null) { public Page<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate, Pageable pageable) {
throw new IllegalArgumentException("Дата 'от' должна быть указана"); 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);
} }
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now()); } else {
return repository.getAll().stream() resultPage = repository.findAll(pageable);
.filter(item -> item.getDate().isAfter(startDate.minusDays(1)) && item.getDate().isBefore(end.plusDays(1))) // использование методов isAfter и isBefore для LocalDate
.collect(Collectors.toList());
} }
public List<IventEntity> getAll() { if (typeId != null && typeId != 0L) {
return repository.getAll(); 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;
}
@Transactional(readOnly = true)
public IventEntity get(Long id) { public IventEntity get(Long id) {
return Optional.ofNullable(repository.get(id)) return repository.findById(id)
.orElseThrow(() -> new NotFoundException(id)); .orElseThrow(() -> new NotFoundException(IventEntity.class, id));
} }
@Transactional
public IventEntity create(IventEntity entity) { 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) { public IventEntity update(Long id, IventEntity entity) {
final IventEntity existsEntity = get(id); final IventEntity existsEntity = get(id);
existsEntity.setName(entity.getName()); existsEntity.setName(entity.getName());
@ -81,11 +123,23 @@ public class IventService {
existsEntity.setPrice(entity.getPrice()); existsEntity.setPrice(entity.getPrice());
existsEntity.setCount(entity.getCount()); existsEntity.setCount(entity.getCount());
existsEntity.setPlace(entity.getPlace()); existsEntity.setPlace(entity.getPlace());
return repository.update(existsEntity); existsEntity.setImage(entity.getImage());
return repository.save(existsEntity);
} }
@Transactional
public IventEntity delete(Long id) { public IventEntity delete(Long id) {
final IventEntity existsEntity = get(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; import jakarta.validation.constraints.NotBlank;
public class PlaceDto { public class PlaceDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
private String name; private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -4,15 +4,20 @@ import java.util.Objects;
import com.example.demo.core.model.BaseEntity; 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 { public class PlaceEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name; private String name;
public PlaceEntity() { public PlaceEntity() {
super();
} }
public PlaceEntity(Long id, String name) { public PlaceEntity(String name) {
super(id);
this.name = name; this.name = name;
} }

View File

@ -1,11 +1,11 @@
package com.example.demo.places.repository; 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; import com.example.demo.places.model.PlaceEntity;
@Repository public interface PlaceRepository extends CrudRepository<PlaceEntity, Long> {
public class PlaceRepository extends MapRepository<PlaceEntity> { Optional<PlaceEntity> findByNameIgnoreCase(String name);
} }

View File

@ -1,9 +1,10 @@
package com.example.demo.places.service; package com.example.demo.places.service;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.places.model.PlaceEntity; import com.example.demo.places.model.PlaceEntity;
@ -17,28 +18,45 @@ public class PlaceService {
this.repository = repository; 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() { public List<PlaceEntity> getAll() {
return repository.getAll(); return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
@Transactional(readOnly = true)
public PlaceEntity get(Long id) { public PlaceEntity get(Long id) {
return Optional.ofNullable(repository.get(id)) return repository.findById(id)
.orElseThrow(() -> new NotFoundException(id)); .orElseThrow(() -> new NotFoundException(PlaceEntity.class, id));
} }
@Transactional
public PlaceEntity create(PlaceEntity entity) { 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) { public PlaceEntity update(Long id, PlaceEntity entity) {
final PlaceEntity existsEntity = get(id); final PlaceEntity existsEntity = get(id);
existsEntity.setName(entity.getName()); existsEntity.setName(entity.getName());
return repository.update(existsEntity); return repository.save(existsEntity);
} }
@Transactional
public PlaceEntity delete(Long id) { public PlaceEntity delete(Long id) {
final PlaceEntity existsEntity = get(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; import jakarta.validation.constraints.NotBlank;
public class TypeDto { public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
private String name; private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -4,15 +4,20 @@ import java.util.Objects;
import com.example.demo.core.model.BaseEntity; 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 { public class TypeEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name; private String name;
public TypeEntity() { public TypeEntity() {
super();
} }
public TypeEntity(Long id, String name) { public TypeEntity(String name) {
super(id);
this.name = name; this.name = name;
} }

View File

@ -1,11 +1,11 @@
package com.example.demo.types.repository; 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; import com.example.demo.types.model.TypeEntity;
@Repository public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
public class TypeRepository extends MapRepository<TypeEntity> { Optional<TypeEntity> findByNameIgnoreCase(String name);
} }

View File

@ -1,9 +1,10 @@
package com.example.demo.types.service; package com.example.demo.types.service;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.types.model.TypeEntity; import com.example.demo.types.model.TypeEntity;
@ -17,28 +18,45 @@ public class TypeService {
this.repository = repository; 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() { public List<TypeEntity> getAll() {
return repository.getAll(); return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
@Transactional(readOnly = true)
public TypeEntity get(Long id) { public TypeEntity get(Long id) {
return Optional.ofNullable(repository.get(id)) return repository.findById(id)
.orElseThrow(() -> new NotFoundException(id)); .orElseThrow(() -> new NotFoundException(TypeEntity.class, id));
} }
@Transactional
public TypeEntity create(TypeEntity entity) { 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) { public TypeEntity update(Long id, TypeEntity entity) {
final TypeEntity existsEntity = get(id); final TypeEntity existsEntity = get(id);
existsEntity.setName(entity.getName()); existsEntity.setName(entity.getName());
return repository.update(existsEntity); return repository.save(existsEntity);
} }
@Transactional
public TypeEntity delete(Long id) { public TypeEntity delete(Long id) {
final TypeEntity existsEntity = get(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; package com.example.demo.users.api;
import java.util.List;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; 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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; 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.core.configuration.Constants;
import com.example.demo.users.model.UserEntity; import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService; import com.example.demo.users.service.UserService;
@ -38,8 +39,10 @@ public class UserController {
} }
@GetMapping @GetMapping
public List<UserDto> getAll() { public PageDto<UserDto> getAll(
return userService.getAll().stream().map(this::toDto).toList(); @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}") @GetMapping("/{id}")
@ -53,7 +56,7 @@ public class UserController {
} }
@PutMapping("/{id}") @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))); 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 com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto { public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
private String handle; private String handle;
@ -12,8 +14,10 @@ public class UserDto {
private String email; private String email;
@NotBlank @NotBlank
private String password; private String password;
@NotBlank
@Size(min = 1, max = 20)
private String accessLevel;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { public Long getId() {
return id; return id;
} }
@ -45,5 +49,13 @@ public class UserDto {
public void setPassword(String password) { public void setPassword(String password) {
this.password = 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 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 { public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String handle; private String handle;
@Column(nullable = false, unique = true)
private String email; private String email;
@Column(nullable = false)
private String password; private String password;
@Column(nullable = false)
private String accessLevel;
public UserEntity() { public UserEntity() {
super();
} }
public UserEntity(Long id, String handle, String email, String password) { public UserEntity(String handle, String email, String password, String accessLevel) {
super(id);
this.handle = handle; this.handle = handle;
this.email = email; this.email = email;
this.password = password; this.password = password;
this.accessLevel = accessLevel;
} }
public String getHandle() { public String getHandle() {
@ -44,9 +57,17 @@ public class UserEntity extends BaseEntity {
this.password = password; this.password = password;
} }
public String getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
}
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, handle, email, password); return Objects.hash(id, handle, email, password, accessLevel);
} }
@Override @Override
@ -59,7 +80,8 @@ public class UserEntity extends BaseEntity {
return Objects.equals(other.getId(), id) return Objects.equals(other.getId(), id)
&& Objects.equals(other.getHandle(), handle) && Objects.equals(other.getHandle(), handle)
&& Objects.equals(other.getEmail(), email) && 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; 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; import com.example.demo.users.model.UserEntity;
@Repository public interface UserRepository
public class UserRepository extends MapRepository<UserEntity> { extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
Optional<UserEntity> findByHandleIgnoreCase(String handle);
} }

View File

@ -1,9 +1,12 @@
package com.example.demo.users.service; package com.example.demo.users.service;
import java.util.List; 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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity; import com.example.demo.users.model.UserEntity;
@ -17,28 +20,54 @@ public class UserService {
this.repository = repository; 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() { public List<UserEntity> getAll() {
return repository.getAll(); return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
public UserEntity get(Long id) { @Transactional(readOnly = true)
return Optional.ofNullable(repository.get(id)) public Page<UserEntity> getAll(int page, int size) {
.orElseThrow(() -> new NotFoundException(id)); 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) { 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); final UserEntity existsEntity = get(id);
existsEntity.setHandle(entity.getHandle()); 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); 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
spring.main.banner-mode=off
server.port=8081 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.time.LocalDate;
import java.util.List; 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.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; 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.model.IventEntity;
import com.example.demo.ivents.service.IventService; 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.places.service.PlaceService;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import jakarta.persistence.EntityManager;
@SpringBootTest @SpringBootTest
@TestMethodOrder(OrderAnnotation.class) @TestMethodOrder(OrderAnnotation.class)
class IventServiceTests { class IventServiceTests {
@ -31,53 +38,73 @@ class IventServiceTests {
@Autowired @Autowired
private IventService iventService; 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 @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() { void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> iventService.get(0L)); Assertions.assertThrows(NotFoundException.class, () -> iventService.get(0L));
} }
@Test @Test
@Order(1) @Order(3)
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)
void sortDates() { void sortDates() {
LocalDate start = LocalDate.of(2024, 1, 15); LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate end = LocalDate.of(2024, 5, 15); LocalDate end = LocalDate.of(2024, 5, 15);
@ -88,17 +115,34 @@ class IventServiceTests {
} }
@Test @Test
@Order(3) @Order(4)
void updateTest() { void createNullableTest() {
final TypeEntity type = typeService.create(new TypeEntity(null, "Кино")); final IventEntity nullIvent = new IventEntity(
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(
null, 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, test,
type, type,
LocalDate.of(2023, 10, 15), LocalDate.of(2023, 10, 15),
@ -106,9 +150,10 @@ class IventServiceTests {
"Участниками Radiohead являются:<....>", "Участниками Radiohead являются:<....>",
2500.33, 2500.33,
30, 30,
place)); place,
Assertions.assertEquals(3, iventService.getAll().size()); ""));
Assertions.assertEquals(newEntity, iventService.get(3L)); Assertions.assertEquals(3, iventService.getAll(0L, 0L, null, null).size());
Assertions.assertEquals(newEntity, iventService.get(ivent.getId()));
Assertions.assertEquals(test, newEntity.getName()); Assertions.assertEquals(test, newEntity.getName());
Assertions.assertEquals(type, newEntity.getType()); Assertions.assertEquals(type, newEntity.getType());
Assertions.assertEquals(place, newEntity.getPlace()); Assertions.assertEquals(place, newEntity.getPlace());
@ -118,26 +163,16 @@ class IventServiceTests {
} }
@Test @Test
@Order(4) @Order(6)
void deleteTest() { void deleteTest() {
iventService.delete(3L); iventService.delete(ivent.getId());
Assertions.assertEquals(2, iventService.getAll().size()); Assertions.assertEquals(2, iventService.getAll(0L, 0L, null, null).size());
final IventEntity last = iventService.get(2L);
Assertions.assertEquals(2L, last.getId());
final TypeEntity type = typeService.create(new TypeEntity(null, "Концерт")); final IventEntity newEntity = iventService.create(new IventEntity(ivent.getName(), ivent.getType(),
final PlaceEntity place = placeService.create(new PlaceEntity(null, "USA, California")); ivent.getDate(), ivent.getDesc(), ivent.getOther(), ivent.getPrice(), ivent.getCount(),
final IventEntity newEntity = iventService.create(new IventEntity( ivent.getPlace(), ivent.getImage()));
null, Assertions.assertEquals(1, typeService.getAll().size());
"Deftones", Assertions.assertEquals(1, placeService.getAll().size());
type, Assertions.assertNotEquals(ivent.getId(), newEntity.getId());
LocalDate.of(2023, 10, 15),
"Deftones - американская альтернативная метал-группа, сформированная в 1988 году. ",
"Участники Deftones:<....>",
2550.33,
25,
place));
Assertions.assertEquals(3, iventService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
} }
} }

View File

@ -1,62 +1,81 @@
package com.example.demo; package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.places.model.PlaceEntity; import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService; import com.example.demo.places.service.PlaceService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
@SpringBootTest @SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class PlaceServiceTests { class PlaceServiceTests {
@Autowired @Autowired
private PlaceService placeService; 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 @Test
void getTest() { void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> placeService.get(0L)); Assertions.assertThrows(NotFoundException.class, () -> placeService.get(0L));
} }
@Test @Test
@Order(1)
void createTest() { 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(3, placeService.getAll().size());
Assertions.assertEquals(last, placeService.get(3L)); Assertions.assertEquals(place, placeService.get(place.getId()));
}
@Test
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 @Test
@Order(2)
void updateTest() { void updateTest() {
final String test = "TEST"; final String test = "TEST";
final PlaceEntity entity = placeService.get(3L); final String oldName = place.getName();
final String oldName = entity.getName(); final PlaceEntity newEntity = placeService.update(place.getId(), new PlaceEntity(test));
final PlaceEntity newEntity = placeService.update(3L, new PlaceEntity(1L, test));
Assertions.assertEquals(3, placeService.getAll().size()); 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.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName()); Assertions.assertNotEquals(oldName, newEntity.getName());
} }
@Test @Test
@Order(3)
void deleteTest() { void deleteTest() {
placeService.delete(3L); placeService.delete(place.getId());
Assertions.assertEquals(2, placeService.getAll().size()); Assertions.assertEquals(2, placeService.getAll().size());
final PlaceEntity last = placeService.get(2L);
Assertions.assertEquals(2L, last.getId());
final PlaceEntity newEntity = placeService.create(new PlaceEntity(null, "UK, London")); final PlaceEntity newEntity = placeService.create(new PlaceEntity(place.getName()));
Assertions.assertEquals(3, placeService.getAll().size()); Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId()); Assertions.assertNotEquals(place.getId(), newEntity.getId());
} }
} }

View File

@ -1,61 +1,79 @@
package com.example.demo; package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.types.model.TypeEntity; import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService; import com.example.demo.types.service.TypeService;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
@SpringBootTest @SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class TypeServiceTests { class TypeServiceTests {
@Autowired @Autowired
private TypeService typeService; 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 @Test
void getTest() { void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L)); Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
} }
@Test @Test
@Order(1)
void createTest() { 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(3, typeService.getAll().size());
Assertions.assertEquals(last, typeService.get(3L)); Assertions.assertEquals(type, typeService.get(type.getId()));
}
@Test
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 @Test
@Order(2)
void updateTest() { void updateTest() {
final String test = "TEST"; final String test = "TEST";
final TypeEntity entity = typeService.get(3L); final String oldName = type.getName();
final String oldName = entity.getName(); final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test));
final TypeEntity newEntity = typeService.update(3L, new TypeEntity(1L, test));
Assertions.assertEquals(3, typeService.getAll().size()); 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.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName()); Assertions.assertNotEquals(oldName, newEntity.getName());
} }
@Test @Test
@Order(3)
void deleteTest() { void deleteTest() {
typeService.delete(3L); typeService.delete(type.getId());
Assertions.assertEquals(2, typeService.getAll().size()); Assertions.assertEquals(2, typeService.getAll().size());
final TypeEntity last = typeService.get(2L);
Assertions.assertEquals(2L, last.getId());
final TypeEntity newEntity = typeService.create(new TypeEntity(null, "Театр")); final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName()));
Assertions.assertEquals(3, typeService.getAll().size()); Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId()); Assertions.assertNotEquals(type.getId(), newEntity.getId());
} }
} }

View File

@ -1,62 +1,86 @@
package com.example.demo; package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; 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.model.UserEntity;
import com.example.demo.users.service.UserService; import com.example.demo.users.service.UserService;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
@SpringBootTest @SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserServiceTests { class UserServiceTests {
@Autowired @Autowired
private UserService userService; 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 @Test
void getTest() { void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L)); Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
} }
@Transactional
@Test @Test
@Order(1)
void createTest() { 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(3, userService.getAll().size());
Assertions.assertEquals(last, userService.get(3L)); Assertions.assertEquals(user, userService.get(user.getId()));
} }
@Test @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() { void updateTest() {
final String test = "TEST"; final String test = "TEST";
final UserEntity entity = userService.get(3L); final String oldLogin = user.getHandle();
final String oldName = entity.getHandle(); final UserEntity newEntity = userService.update(user.getId(),
final UserEntity newEntity = userService.update(3L, new UserEntity(1L, test, "user@gmail.com", "test")); new UserEntity(test, "admin@gmail.com", "admin", "admin"));
Assertions.assertEquals(3, userService.getAll().size()); 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.assertEquals(test, newEntity.getHandle());
Assertions.assertNotEquals(oldName, newEntity.getHandle()); Assertions.assertNotEquals(oldLogin, newEntity.getHandle());
} }
@Test @Test
@Order(3)
void deleteTest() { void deleteTest() {
userService.delete(3L); userService.delete(user.getId());
Assertions.assertEquals(2, userService.getAll().size()); 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(3, userService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId()); Assertions.assertNotEquals(user.getId(), newEntity.getId());
} }
} }