Плохо работают запросы Т-Т

This commit is contained in:
Максим Яковлев 2024-04-13 21:44:13 +04:00
parent 28dcd5bbc2
commit a7b9355739
39 changed files with 674 additions and 495 deletions

BIN
data.mv.db Normal file

Binary file not shown.

135
data.trace.db Normal file
View File

@ -0,0 +1,135 @@
2024-04-13 20:42:31.143812+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT * FROM ORDERS ORDERS [*]USERS TYPES ORDERS_GAMES"
Syntax error in SQL statement "SELECT * FROM ORDERS ORDERS [*]USERS TYPES ORDERS_GAMES"; SQL statement:
SELECT * FROM ORDERS ORDERS USERS TYPES ORDERS_GAMES [42000-224]
2024-04-13 20:42:31.965718+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT * FROM ORDERS ORDERS [*]USERS TYPES ORDERS_GAMES"
Syntax error in SQL statement "SELECT * FROM ORDERS ORDERS [*]USERS TYPES ORDERS_GAMES"; SQL statement:
SELECT * FROM ORDERS ORDERS USERS TYPES ORDERS_GAMES [42000-224]
2024-04-13 21:20:26.232539+04:00 jdbc[3]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Значения типов данных "BIGINT" и "ROW(C1 UNKNOWN, C2 UNKNOWN)" не сравнимы друг с другом
Values of types "BIGINT" and "ROW(C1 UNKNOWN, C2 UNKNOWN)" are not comparable; SQL statement:
select ge1_0.id,ge1_0.description,ge1_0.name,ge1_0.price,ge1_0.type_id from games ge1_0 left join types t1_0 on t1_0.id=ge1_0.type_id left join games_genres g1_0 on ge1_0.id=g1_0.game_entity_id where t1_0.id=? and g1_0.genres_id=(?,?) offset ? rows fetch first ? rows only [90110-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:644)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.value.TypeInfo.checkComparable(TypeInfo.java:766)
at org.h2.expression.condition.Comparison.optimize(Comparison.java:167)
at org.h2.expression.condition.ConditionAndOr.optimize(ConditionAndOr.java:137)
at org.h2.expression.Expression.optimizeCondition(Expression.java:148)
at org.h2.command.query.Select.prepareExpressions(Select.java:1177)
at org.h2.command.query.Query.prepare(Query.java:218)
at org.h2.command.Parser.prepareCommand(Parser.java:489)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:639)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:559)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1166)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:93)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:316)
at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:327)
at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:153)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:183)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:155)
at org.hibernate.sql.exec.spi.JdbcSelectExecutor.lambda$list$0(JdbcSelectExecutor.java:85)
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.executeQuery(DeferredResultSetAccess.java:231)
at org.hibernate.sql.results.jdbc.internal.DeferredResultSetAccess.getResultSet(DeferredResultSetAccess.java:167)
at org.hibernate.sql.results.jdbc.internal.JdbcValuesResultSetImpl.advanceNext(JdbcValuesResultSetImpl.java:218)
at org.hibernate.sql.results.jdbc.internal.JdbcValuesResultSetImpl.processNext(JdbcValuesResultSetImpl.java:98)
at org.hibernate.sql.results.jdbc.internal.AbstractJdbcValues.next(AbstractJdbcValues.java:19)
at org.hibernate.sql.results.internal.RowProcessingStateStandardImpl.next(RowProcessingStateStandardImpl.java:66)
at org.hibernate.sql.results.spi.ListResultsConsumer.consume(ListResultsConsumer.java:180)
at org.hibernate.sql.results.spi.ListResultsConsumer.consume(ListResultsConsumer.java:33)
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.doExecuteQuery(JdbcSelectExecutorStandardImpl.java:209)
at org.hibernate.sql.exec.internal.JdbcSelectExecutorStandardImpl.executeQuery(JdbcSelectExecutorStandardImpl.java:83)
at org.hibernate.sql.exec.spi.JdbcSelectExecutor.list(JdbcSelectExecutor.java:76)
at org.hibernate.sql.exec.spi.JdbcSelectExecutor.list(JdbcSelectExecutor.java:65)
at org.hibernate.query.sqm.internal.ConcreteSqmSelectQueryPlan.lambda$new$2(ConcreteSqmSelectQueryPlan.java:137)
at org.hibernate.query.sqm.internal.ConcreteSqmSelectQueryPlan.withCacheableSqmInterpretation(ConcreteSqmSelectQueryPlan.java:362)
at org.hibernate.query.sqm.internal.ConcreteSqmSelectQueryPlan.performList(ConcreteSqmSelectQueryPlan.java:303)
at org.hibernate.query.sqm.internal.QuerySqmImpl.doList(QuerySqmImpl.java:509)
at org.hibernate.query.spi.AbstractSelectionQuery.list(AbstractSelectionQuery.java:427)
at org.hibernate.query.Query.getResultList(Query.java:120)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:204)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:92)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:149)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:137)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:170)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:158)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:143)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:392)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:220)
at jdk.proxy2/jdk.proxy2.$Proxy124.findByTypeIdAndGenres(Unknown Source)
at com.example.demo.games.service.GameService.getAll(GameService.java:29)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:351)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:765)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:392)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:765)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:717)
at com.example.demo.games.service.GameService$$SpringCGLIB$$0.getAll(<generated>)
at com.example.demo.games.api.GameController.getAll(GameController.java:70)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:255)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:188)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:925)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:830)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1089)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
at java.base/java.lang.Thread.run(Thread.java:1623)

View File

@ -3,11 +3,12 @@ package com.example.demo;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService; import com.example.demo.games.service.GameService;
@ -22,9 +23,9 @@ import com.example.demo.users.service.UserService;
@SpringBootApplication @SpringBootApplication
@RestController
@RequestMapping("/api")
public class DemoApplication implements CommandLineRunner { public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final TypeService typeService; private final TypeService typeService;
private final GenreService genreService; private final GenreService genreService;
private final GameService gameService; private final GameService gameService;
@ -39,13 +40,18 @@ public class DemoApplication implements CommandLineRunner {
this.userService = userService; this.userService = userService;
} }
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override @Override
public void run(String... args) throws Exception{ public void run(String... args) throws Exception{
final var type1 = typeService.create(new TypeEntity(null,"ААА")); log.info("start");
final var type2 = typeService.create(new TypeEntity(null,"АА")); final var type1 = typeService.create(new TypeEntity("ААА"));
final var type2 = typeService.create(new TypeEntity("АА"));
final var genre1 = genreService.create(new GenreEntity(null, "Приключения")); final var genre1 = genreService.create(new GenreEntity("Приключения"));
final var genre2 = genreService.create(new GenreEntity(null, "Симулятор")); final var genre2 = genreService.create(new GenreEntity("Симулятор"));
final List<GenreEntity> genres1 = new ArrayList<GenreEntity>(); final List<GenreEntity> genres1 = new ArrayList<GenreEntity>();
genres1.add(genre1); genres1.add(genre1);
@ -54,20 +60,16 @@ public class DemoApplication implements CommandLineRunner {
final List<GenreEntity> genres2 = new ArrayList<GenreEntity>(); final List<GenreEntity> genres2 = new ArrayList<GenreEntity>();
genres2.add(genre2); genres2.add(genre2);
final var game1 = gameService.create(new GameEntity(null,type1,"Game1",2100.0,"good game", genres1)); final var game1 = gameService.create(new GameEntity(type1,"Game1",2100.0,"good game", genres1));
final var game2 = gameService.create(new GameEntity(null, type2, "Game2", 1200.0,"bad game", genres2)); // final var game2 = gameService.create(new GameEntity( type2, "Game2", 1200.0,"bad game", genres2));
final List<GameEntity> games = new ArrayList<GameEntity>(); // final List<GameEntity> games = new ArrayList<GameEntity>();
games.add(game1); // games.add(game1);
games.add(game2); // games.add(game2);
userService.create(new UserEntity(null, "login1", "email@mail.com", "qwerty123")); // var user1 = userService.create(new UserEntity( "login1", "email@mail.com", "qwerty123"));
userService.create(new UserEntity(null, "login2", "email@gmail.com", "qwerty1234")); // var user2 = userService.create(new UserEntity( "login2", "email@gmail.com", "qwerty1234"));
orderService.create(new OrderEntity(null, 1L,games)); // orderService.create(1, new OrderEntity(user1,games));
orderService.create(new OrderEntity(null, 2L,games)); // orderService.create(1, new OrderEntity(user1,games));
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }
} }

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

@ -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,15 +1,23 @@
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() {
} }
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -1,17 +0,0 @@
package com.example.demo.core.repository;
import java.util.List;
public interface CommonRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -1,57 +0,0 @@
package com.example.demo.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.demo.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final Map<Long, E> entities = new TreeMap<>();
private Long lastId = 0L;
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Long id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public E delete(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.remove(entity.getId());
return entity;
}
@Override
public void deleteAll() {
lastId = 0L;
entities.clear();
}
}

View File

@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; 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.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService; import com.example.demo.games.service.GameService;
@ -60,8 +62,13 @@ public class GameController {
} }
@GetMapping @GetMapping
public List<GameDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId, @RequestParam(name = "genres", defaultValue = "") List<Long> genres){ public PageDto<GameDto> getAll(
return gameService.getAll(typeId, genres).stream().map(this::toDto).toList(); @RequestParam(name = "typeId", defaultValue = "0") Long typeId,
//@RequestParam(name = "genres", defaultValue = "") List<Long> genres,
@RequestParam(name = "genres", defaultValue = "") Long genre,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size){
return PageDtoMapper.toDto(gameService.getAll(typeId, genre, page, size), this::toDto);
} }
@GetMapping("/{id}") @GetMapping("/{id}")

View File

@ -10,6 +10,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
public class GameDto { public class GameDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1) @Min(1)
@ -24,7 +25,6 @@ public class GameDto {
@NotBlank @NotBlank
private String description; private String description;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId(){ public Long getId(){
return id; return id;
} }

View File

@ -8,19 +8,32 @@ import com.example.demo.core.model.BaseEntity;
import com.example.demo.genres.model.GenreEntity; import com.example.demo.genres.model.GenreEntity;
import com.example.demo.types.model.TypeEntity; import com.example.demo.types.model.TypeEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "games")
public class GameEntity extends BaseEntity{ public class GameEntity extends BaseEntity{
@Column(nullable = false)
private String name; private String name;
@Column(nullable = false)
private Double price; private Double price;
@Column(nullable = false)
private String description; private String description;
@OneToMany
private final List<GenreEntity> genres = new ArrayList<>(); private final List<GenreEntity> genres = new ArrayList<>();
@OneToOne
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type; private TypeEntity type;
public GameEntity(){ public GameEntity(){
super();
} }
public GameEntity(Long id, TypeEntity type, String name, Double price, String description, List<GenreEntity> genres){ public GameEntity(TypeEntity type, String name, Double price, String description, List<GenreEntity> genres){
super(id);
this.type = type; this.type = type;
this.name = name; this.name = name;
this.price = price; this.price = price;

View File

@ -1,11 +1,17 @@
package com.example.demo.games.repository; package com.example.demo.games.repository;
import org.springframework.stereotype.Repository; import java.util.Optional;
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.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
@Repository public interface GameRepository extends CrudRepository<GameEntity, Long>, PagingAndSortingRepository<GameEntity, Long> {
public class GameRepository extends MapRepository<GameEntity>{ Optional<GameEntity> findOneById(Long id);
Page<GameEntity> findByTypeIdAndGenres(long typeId, Long genres, Pageable pageable);
Page<GameEntity> findByTypeId(long typeId, Pageable pageable);
Page<GameEntity> findByGenres(Long genres, Pageable pageable);
} }

View File

@ -1,11 +1,12 @@
package com.example.demo.games.service; package com.example.demo.games.service;
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 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 org.springframework.data.domain.Pageable;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
@ -15,40 +16,58 @@ import com.example.demo.genres.service.GenreService;
@Service @Service
public class GameService { public class GameService {
private final GameRepository repository; private final GameRepository repository;
private final GenreService genreService;
public GameService(GameRepository repository, GenreService genreService){ public GameService(GameRepository repository, GenreService genreService){
this.repository = repository; this.repository = repository;
this.genreService = genreService;
} }
public List<GameEntity> getAll(Long typeId, List<Long> genres){ // @Transactional(readOnly = true)
// public Page<GameEntity> getAll(Long typeId, List<Long> genres, int page, int size){
// final Pageable pageRequest = PageRequest.of(page, size);
var genresEnt = new ArrayList<>(); // if(!Objects.equals(typeId, 0L) && !Objects.equals(genres.size(), 0)){
for(var genreid : genres){ // return repository.findByTypeIdAndGenres(typeId, genres, pageRequest);
genresEnt.add(genreService.get(genreid)); // }
} // if(Objects.equals(typeId, 0L) && !Objects.equals(genres.size(), 0)){
// return repository.findByGenres(genres, pageRequest);
// }
// if(!Objects.equals(typeId, 0L) && Objects.equals(genres.size(), 0)){
// return repository.findByTypeId(typeId, pageRequest);
// }
// return repository.findAll(PageRequest.of(page, size));
// }
//getAll.stream().filter(game -> game.getType().getId().equals(typeId)).toList();
if(!Objects.equals(typeId, 0L) && !Objects.equals(genresEnt.size(), 0)){ @Transactional(readOnly = true)
return repository.getAll().stream().filter(game -> game.getType().getId().equals(typeId) && game.getGenres().containsAll(genresEnt)).toList(); public Page<GameEntity> getAll(Long typeId, Long genre, int page, int size){
final Pageable pageRequest = PageRequest.of(page, size);
if(!Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){
return repository.findByTypeIdAndGenres(typeId, genre, pageRequest);
} }
if(Objects.equals(typeId, 0L) && !Objects.equals(genresEnt.size(), 0)){ if(Objects.equals(typeId, 0L) && !Objects.equals(genre, 0L)){
return repository.getAll().stream().filter(game -> game.getGenres().containsAll(genresEnt)).toList(); return repository.findByGenres(genre, pageRequest);
} }
if(!Objects.equals(typeId, 0L) && Objects.equals(genresEnt.size(), 0)){ if(!Objects.equals(typeId, 0L) && Objects.equals(genre, 0L)){
return repository.getAll().stream().filter(game -> game.getType().getId().equals(typeId)).toList(); return repository.findByTypeId(typeId, pageRequest);
} }
return repository.getAll(); return repository.findAll(pageRequest);
} }
@Transactional(readOnly = true)
public GameEntity get(Long id){ public GameEntity get(Long id){
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id)); return repository.findOneById(id).orElseThrow(() -> new NotFoundException(GameEntity.class, id));
} }
@Transactional
public GameEntity create(GameEntity entity){ public GameEntity create(GameEntity entity){
return repository.create(entity); if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
} }
@Transactional
public GameEntity update(Long id, GameEntity entity){ public GameEntity update(Long id, GameEntity entity){
final GameEntity existEntity = get(id); final GameEntity existEntity = get(id);
existEntity.setName(entity.getName()); existEntity.setName(entity.getName());
@ -59,11 +78,13 @@ public class GameService {
for(var genre : genres){ for(var genre : genres){
existEntity.setGenres(genre); existEntity.setGenres(genre);
} }
return repository.update(existEntity); return repository.save(existEntity);
} }
@Transactional
public GameEntity delete(Long id){ public GameEntity delete(Long id){
final GameEntity existEntity = get(id); final GameEntity existEntity = get(id);
return repository.delete(existEntity); repository.delete(existEntity);
return existEntity;
} }
} }

View File

@ -2,20 +2,20 @@ package com.example.demo.genres.api;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size;
public class GenreDto { public class GenreDto {
private Long id;
@NotNull
@Min(1)
private String name;
@NotNull
@JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { private Long id;
@NotBlank
@Size(min = 1, max = 50)
private String name;
public Long getId(){
return id; return id;
} }
public void setId(Long id){ public void setId(Long id){
this.id = id; this.id = id;
} }
@ -23,6 +23,7 @@ public class GenreDto {
public String getName(){ public String getName(){
return name; return name;
} }
public void setName(String name){ public void setName(String name){
this.name = name; this.name = name;
} }

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 = "genres")
public class GenreEntity extends BaseEntity { public class GenreEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name; private String name;
public GenreEntity(){ public GenreEntity(){
super();
} }
public GenreEntity(Long id, String name){ public GenreEntity(String name){
super(id);
this.name = name; this.name = name;
} }

View File

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

View File

@ -1,7 +1,9 @@
package com.example.demo.genres.service; package com.example.demo.genres.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.stream.StreamSupport;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.genres.model.GenreEntity; import com.example.demo.genres.model.GenreEntity;
@ -17,26 +19,35 @@ public class GenreService {
this.repository = repository; this.repository = repository;
} }
@Transactional(readOnly = true)
public List<GenreEntity> getAll(){ public List<GenreEntity> getAll(){
return repository.getAll(); return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
@Transactional(readOnly = true)
public GenreEntity get(Long id){ public GenreEntity get(Long id){
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id)); return repository.findById(id).orElseThrow(() -> new NotFoundException(GenreEntity.class, id));
} }
@Transactional
public GenreEntity create(GenreEntity entity){ public GenreEntity create(GenreEntity entity){
return repository.create(entity); if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
} }
@Transactional
public GenreEntity update(Long id, GenreEntity entity){ public GenreEntity update(Long id, GenreEntity entity){
final GenreEntity exisEntity = get(id); final GenreEntity exisEntity = get(id);
exisEntity.setName(entity.getName()); exisEntity.setName(entity.getName());
return repository.update(exisEntity); return repository.save(exisEntity);
} }
@Transactional
public GenreEntity delete(Long id){ public GenreEntity delete(Long id){
final GenreEntity existEntity = get(id); final GenreEntity existEntity = get(id);
return repository.delete(existEntity); repository.delete(existEntity);
return existEntity;
} }
} }

View File

@ -10,7 +10,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.example.demo.core.configuration.Constants; import com.example.demo.core.configuration.Constants;
import com.example.demo.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
@ -18,33 +17,27 @@ import com.example.demo.games.service.GameService;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService; import com.example.demo.orders.service.OrderService;
import com.example.demo.users.service.UserService; import com.example.demo.users.service.UserService;
import com.example.demo.core.api.PageDtoMapper;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@RestController @RestController
@RequestMapping(Constants.API_URL + "/order") @RequestMapping(Constants.API_URL + "/user/{user}/order")
public class OrderController { public class OrderController {
private final GameService gameService; private final GameService gameService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
private final OrderService orderService; private final OrderService orderService;
//private final UserService userService;
public OrderController(GameService gameService, ModelMapper modelMapper, OrderService orderService, UserService userService){ public OrderController(GameService gameService, ModelMapper modelMapper, OrderService orderService, UserService userService){
this.gameService = gameService; this.gameService = gameService;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
this.orderService = orderService; this.orderService = orderService;
//this.userService = userService;
} }
private OrderDto toDto(OrderEntity entity){ private OrderDto toDto(OrderEntity entity){
var dto = new OrderDto(); var dto = new OrderDto();
dto.setId(entity.getId()); dto.setId(entity.getId());
double sum = 0; dto.setUserId(entity.getUser().getId());
for(var game : entity.getGames()){
sum += game.getPrice();
}
dto.setUserId(entity.getUserId());
dto.setSum(sum);
dto.setGames(entity.getGames().stream().map(GameEntity::getId).toList()); dto.setGames(entity.getGames().stream().map(GameEntity::getId).toList());
return dto; return dto;
} }
@ -59,22 +52,32 @@ public class OrderController {
} }
@GetMapping @GetMapping
public List<OrderDto> getAll(@RequestParam(name = "userId", defaultValue = "") Long userId){ public com.example.demo.core.api.PageDto<OrderDto> getAll(
return orderService.getAll(userId).stream().map(this::toDto).toList(); @RequestParam(name = "userId", defaultValue = "") Long userId,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE)int size){
return PageDtoMapper.toDto(orderService.getAll(userId, page, size), this::toDto);
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public OrderDto get(@PathVariable(name = "id")Long id){ public OrderDto get(
return toDto(orderService.get(id)); @PathVariable(name = "user") Long userId,
@PathVariable(name = "id")Long id) {
return toDto(orderService.get(userId, id));
} }
@PostMapping @PostMapping
public OrderDto create(@RequestBody @Valid OrderDto dto){ public OrderDto create(
return toDto(orderService.create(toEntity(dto))); @PathVariable(name = "user") Long userId,
@RequestBody @Valid OrderDto dto){
return toDto(orderService.create(userId, toEntity(dto)));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public OrderDto delete(@PathVariable(name = "id") Long id){ public OrderDto delete(
return toDto(orderService.delete(id)); @PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id){
return toDto(orderService.delete(userId, id));
} }
} }

View File

@ -9,17 +9,14 @@ import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
public class OrderDto { public class OrderDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1) @Min(1)
private double sum;
@NotNull
@Min(1)
private Long userId; private Long userId;
@NotNull @NotNull
private final List<Long> games = new ArrayList<>(); private final List<Long> games = new ArrayList<>();
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId(){ public Long getId(){
return id; return id;
} }
@ -27,14 +24,6 @@ public class OrderDto {
this.id = id; this.id = id;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public double getSum(){
return sum;
}
public void setSum(double sum){
this.sum = sum;
}
public List<Long> getGames(){ public List<Long> getGames(){
return games; return games;
} }

View File

@ -2,46 +2,60 @@ package com.example.demo.orders.model;
import java.util.List; import java.util.List;
import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.ArrayList;
import com.example.demo.core.model.BaseEntity; import com.example.demo.core.model.BaseEntity;
import com.example.demo.games.model.GameEntity; import com.example.demo.games.model.GameEntity;
import com.example.demo.users.model.UserEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity{ public class OrderEntity extends BaseEntity{
private double sum; // @Column(nullable = false)
private Long userId; // private double sum;
private final List<GameEntity> games = new ArrayList<>(); @ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@OneToMany
private Set<GameEntity> games = new HashSet<>();
public OrderEntity(){ public OrderEntity(){
super();
} }
public OrderEntity(Long id, Long userId, List<GameEntity> games){ public OrderEntity(UserEntity user, List<GameEntity> games){
super(id); this.user = user;
this.userId = userId;
this.games.clear(); this.games.clear();
this.games.addAll(games); this.games.addAll(games);
} }
public double getSum(){ // public double getSum(){
for(var game : games){ // for(var game : games){
sum += game.getPrice(); // sum += game.getPrice();
// }
// return sum;
// }
public UserEntity getUser(){
return user;
}
public void setUser(UserEntity user){
this.user = user;
if(!user.getOrders().contains(this)){
user.getOrders().add(this);
} }
return sum;
} }
public Long getUserId(){ public Set<GameEntity> getGames(){
return userId;
}
public void setUserId(Long userId){
this.userId = userId;
}
public List<GameEntity> getGames(){
return games; return games;
} }
public void setGames(GameEntity game){ public void setGames(GameEntity game){
@ -50,7 +64,7 @@ public class OrderEntity extends BaseEntity{
@Override @Override
public int hashCode(){ public int hashCode(){
return Objects.hash(id, sum, games); return Objects.hash(id, games);
} }
@Override @Override
@ -60,7 +74,7 @@ public class OrderEntity extends BaseEntity{
final OrderEntity other = (OrderEntity) obj; final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id) return Objects.equals(other.getId(), id)
&& Objects.equals(other.getSum(), sum) //&& Objects.equals(other.getSum(), sum)
&& Objects.equals(other.getGames(), games); && Objects.equals(other.getGames(), games);
} }
} }

View File

@ -1,11 +1,22 @@
package com.example.demo.orders.repository; package com.example.demo.orders.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository; import java.util.List;
import java.util.Optional;
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.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
@Repository public interface OrderRepository extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> {
Optional<OrderEntity> findOneByUserIdAndId(long userId, long id);
public class OrderRepository extends MapRepository<OrderEntity>{ List<OrderEntity> findByUserId(long userId);
Page<OrderEntity> findByUserId(long userId, Pageable pageable);
//Можно сделать запрос на сумму JPQL
} }

View File

@ -1,40 +1,63 @@
package com.example.demo.orders.service; package com.example.demo.orders.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Optional;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.repository.OrderRepository; import com.example.demo.orders.repository.OrderRepository;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@Service @Service
public class OrderService { public class OrderService {
private final OrderRepository repository; private final OrderRepository repository;
private final UserService userService;
public OrderService(OrderRepository repository){ public OrderService(OrderRepository repository, UserService userService){
this.repository = repository; this.repository = repository;
this.userService = userService;
} }
public List<OrderEntity> getAll(Long userId){ @Transactional(readOnly = true)
if(!Objects.equals(userId, null)){ public List<OrderEntity> getAll(long userId){
return repository.getAll().stream().filter(user -> user.getId().equals(userId)).toList(); userService.get(userId);
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public Page<OrderEntity> getAll(long userId, int page, int size){
final Pageable pageRequest = PageRequest.of(page, size);
userService.get(userId);
return repository.findByUserId(userId, pageRequest);
}
@Transactional(readOnly = true)
public OrderEntity get(long userId, long id){
userService.get(userId);
return repository.findOneByUserIdAndId(userId, id).orElseThrow(() -> new NotFoundException(OrderEntity.class, id));
}
@Transactional
public OrderEntity create(long userId, OrderEntity entity){
if(entity == null){
throw new IllegalArgumentException("Entity is null");
} }
return repository.getAll(); final UserEntity existsUser = userService.get(userId);
entity.setUser(existsUser);
return repository.save(entity);
} }
public OrderEntity get(Long id){ @Transactional
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id)); public OrderEntity delete(long userId, long id){
} userService.get(userId);
final OrderEntity existsEntity = get(userId, id);
public OrderEntity create(OrderEntity entity){ repository.delete(existsEntity);
return repository.create(entity); return existsEntity;
}
public OrderEntity delete(Long id){
final OrderEntity exisEntity = get(id);
return repository.delete(exisEntity);
} }
} }

View File

@ -3,13 +3,15 @@ package com.example.demo.types.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 TypeDto { public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
@Size(min = 1, max = 50)
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, length = 50)
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 org.springframework.data.repository.CrudRepository;
import com.example.demo.core.repository.MapRepository;
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,11 @@
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,26 +19,35 @@ public class TypeService {
this.repository = repository; this.repository = repository;
} }
@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)).orElseThrow(() -> new NotFoundException(id)); return repository.findById(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");
}
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

@ -8,10 +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 java.util.List; 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.orders.service.OrderService; import com.example.demo.orders.service.OrderService;
import com.example.demo.users.model.UserEntity; import com.example.demo.users.model.UserEntity;
@ -31,22 +32,18 @@ public class UserController {
} }
private UserDto toDto(UserEntity entity){ private UserDto toDto(UserEntity entity){
var dto = new UserDto(); return modelMapper.map(entity, UserDto.class);
dto.setId(entity.getId());
dto.setLogin(entity.getLogin());
dto.setEmail(entity.getEmail());
dto.setPassword(entity.getPassword());
return dto;
} }
private UserEntity toEntity(UserDto dto){ private UserEntity toEntity(UserDto dto){
final UserEntity entity = modelMapper.map(dto, UserEntity.class); return modelMapper.map(dto, UserEntity.class);
return entity;
} }
@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}")

View File

@ -3,17 +3,21 @@ 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
@Size(min = 2, max = 20)
private String login; private String login;
@NotBlank @NotBlank
@Size(min = 2, max = 20)
private String email; private String email;
@NotBlank @NotBlank
@Size(min = 2, max = 20)
private String password; private String password;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId(){ public Long getId(){
return id; return id;
} }

View File

@ -1,18 +1,35 @@
package com.example.demo.users.model; package com.example.demo.users.model;
import com.example.demo.core.model.BaseEntity; import java.util.ArrayList;
import java.util.List;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.orders.model.OrderEntity;
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, length = 20)
private String login; private String login;
@Column(nullable = false, unique = true, length = 20)
private String email; private String email;
@Column(nullable = false, unique = true, length = 20)
private String password; private String password;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private List<OrderEntity> orders = new ArrayList<>();
public UserEntity(){ public UserEntity(){
super();
} }
public UserEntity(Long id, String login, String email, String password){ public UserEntity(String login, String email, String password){
super(id);
this.login = login; this.login = login;
this.email = email; this.email = email;
this.password = password; this.password = password;
@ -38,4 +55,15 @@ public class UserEntity extends BaseEntity{
public void setPassword(String password){ public void setPassword(String password){
this.password = password; this.password = password;
} }
public List<OrderEntity> getOrders(){
return orders;
}
public void addOrder(OrderEntity order){
if(order.getUser() != this){
order.setUser(this);
}
orders.add(order);
}
} }

View File

@ -1,11 +1,12 @@
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 extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
public class UserRepository extends MapRepository<UserEntity> { Optional<UserEntity> findByLoginIgnoreCase(String login);
} }

View File

@ -1,9 +1,13 @@
package com.example.demo.users.service; package com.example.demo.users.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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 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 +21,43 @@ public class UserService {
this.repository = repository; this.repository = repository;
} }
@Transactional(readOnly = true)
public List<UserEntity> getAll(){ public List<UserEntity> getAll(){
return repository.getAll().stream().toList(); return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} }
@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){ public UserEntity get(Long id){
return Optional.ofNullable(repository.get(id)).orElseThrow(()-> new NotFoundException(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");
}
return repository.save(entity);
} }
@Transactional
public UserEntity update(Long id, UserEntity entity){ public UserEntity update(Long id, UserEntity entity){
final UserEntity existEntity = get(id); final UserEntity existEntity = get(id);
existEntity.setLogin(entity.getLogin()); existEntity.setLogin(entity.getLogin());
existEntity.setEmail(entity.getEmail()); existEntity.setEmail(entity.getEmail());
existEntity.setPassword(entity.getPassword()); existEntity.setPassword(entity.getPassword());
return repository.update(existEntity); repository.save(existEntity);
return existEntity;
} }
@Transactional
public UserEntity delete(Long id){ public UserEntity delete(Long id){
final UserEntity existEntity = get(id); final UserEntity existEntity = get(id);
return repository.delete(existEntity); repository.delete(existEntity);
return existEntity;
} }
} }

View File

@ -1 +1,19 @@
spring.main.banner-mode=off
server.port=8080
# 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

@ -1,62 +0,0 @@
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.genres.model.GenreEntity;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class GameServiceTests {
@Autowired
private GameService gameService;
List<GenreEntity> list = new ArrayList<GenreEntity>();
List<Long> list2 = new ArrayList<Long>();
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> gameService.get(0L));
}
@Test
@Order(1)
void createTest(){
list.add(new GenreEntity(null, "приключения"));
list.add(new GenreEntity(null, "Симулятор"));
gameService.create(new GameEntity(null, null, "Game", 210.0, "cool game", list));
gameService.create(new GameEntity(null, null, "VideoGame", 2100.0, "very cool game", list));
Assertions.assertEquals(4, gameService.getAll(0L,list2).size());
}
@Test
@Order(2)
void updateTest(){
final GameEntity newGame = new GameEntity(null, null, "Programm", 1500.0, "cool not game", list);
final GameEntity updGame = gameService.update(2L, newGame);
Assertions.assertEquals(4, gameService.getAll(0L, list2).size());
Assertions.assertEquals(updGame, gameService.get(2L));
Assertions.assertEquals(newGame.getName(), updGame.getName());
Assertions.assertEquals(newGame.getDescription(), updGame.getDescription());
Assertions.assertEquals(newGame.getPrice(), updGame.getPrice());
}
@Test
@Order(3)
void deleteTest(){
gameService.delete(2L);
Assertions.assertEquals(3L, gameService.getAll(0L,list2).size());
}
}

View File

@ -1,52 +0,0 @@
package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.games.model.GameEntity;
import com.example.demo.games.service.GameService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class OrderServiceTest {
@Autowired
private OrderService orderService;
@Autowired
private GameService gameService;
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> orderService.get(0L));
}
@Test
@Order(1)
void createTest(){
final List<GameEntity> games = new ArrayList<GameEntity>();
games.add(gameService.get(1L));
orderService.create(new OrderEntity(null, 1L,games));
final var last = orderService.create(new OrderEntity(null, 2L,games));
Assertions.assertEquals(4, orderService.getAll(null).size());
Assertions.assertEquals(last, orderService.get(4L));
}
@Test
@Order(2)
void deleteTest(){
orderService.delete(2L);
Assertions.assertEquals(3, orderService.getAll(null).size());
final OrderEntity last = orderService.get(1L);
Assertions.assertEquals(1L, last.getId());
}
}

View File

@ -1,58 +0,0 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class TypeServiceTests {
@Autowired
private TypeService typeService;
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
}
@Test
@Order(1)
void createTest(){
typeService.create(new TypeEntity(null, "Игра"));
typeService.create(new TypeEntity(null, "Программа"));
final TypeEntity last = typeService.create(new TypeEntity(null, "Игра2"));
Assertions.assertEquals(5, typeService.getAll().size());
Assertions.assertEquals(last, typeService.get(5L));
}
@Test
@Order(2)
void updateTest(){
final String test = "TEST";
final TypeEntity newEntity = typeService.update(5L, new TypeEntity(1L, test));
Assertions.assertEquals(5, typeService.getAll().size());
Assertions.assertEquals(newEntity, typeService.get(5L));
Assertions.assertEquals(test, newEntity.getName());
}
@Test
@Order(3)
void deleteTest(){
typeService.delete(5L);
Assertions.assertEquals(4, typeService.getAll().size());
final TypeEntity last = typeService.get(4L);
Assertions.assertEquals(4L, last.getId());
final TypeEntity newEntity = typeService.create(new TypeEntity(null, "Игра"));
Assertions.assertEquals(5, typeService.getAll().size());
Assertions.assertEquals(6L, newEntity.getId());
}
}

View File

@ -1,48 +0,0 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class UserServiceTest {
@Autowired
UserService userService;
@Test
void getTest(){
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
@Order(1)
void createTest(){
userService.create(new UserEntity(null, "login5", "gmail", "qwert123"));
final UserEntity last = userService.create(new UserEntity(null, "login6", "mail", "qwer123"));
Assertions.assertEquals(4, userService.getAll().size());
Assertions.assertEquals(last, userService.get(4L));
}
@Test
@Order(2)
void updateTest(){
userService.update(4L, new UserEntity(null,"login","email", "qwe123"));
Assertions.assertEquals(4, userService.getAll().size());
}
@Test
@Order(3)
void deleteTest(){
userService.delete(2L);
Assertions.assertEquals(3, userService.getAll().size());
}
}

View File

@ -0,0 +1,14 @@
# Server
spring.main.banner-mode=off
# 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:mem:testdb
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