Lab 3 done

This commit is contained in:
Artyom_Yashin 2024-04-19 15:09:26 +04:00
parent f9b7ee5825
commit 7f838ba021
40 changed files with 1512 additions and 199 deletions

View File

@ -7,6 +7,17 @@ plugins {
group = 'IP_2' group = 'IP_2'
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'
} }
@ -20,6 +31,9 @@ dependencies {
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'
developmentOnly 'org.springframework.boot:spring-boot-devtools' developmentOnly 'org.springframework.boot:spring-boot-devtools'
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.

449
data.trace.db Normal file
View File

@ -0,0 +1,449 @@
2024-04-18 18:25:59.368842+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "USERSREVIEWS" не найдена
Table "USERSREVIEWS" not found; SQL statement:
SELECT * FROM USERSREVIEWS [42102-224]
2024-04-18 18:26:39.326881+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "USERS.USER_ID" не найден
Column "USERS.USER_ID" not found; SQL statement:
SELECT * FROM reviews join users on users.user_id [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
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.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:31:18.587415+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "R.USERS_ID" не найден
Column "R.USERS_ID" not found; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.users_id [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.condition.Comparison.optimize(Comparison.java:148)
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.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:31:26.826213+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U.LOGIN" должен быть в предложении GROUP BY
Column "U.LOGIN" must be in the GROUP BY list; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id [90016-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.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.updateAggregate(ExpressionColumn.java:266)
at org.h2.expression.Alias.updateAggregate(Alias.java:74)
at org.h2.command.query.Select.updateAgg(Select.java:539)
at org.h2.command.query.Select.gatherGroup(Select.java:522)
at org.h2.command.query.Select.queryGroup(Select.java:488)
at org.h2.command.query.Select.queryWithoutCache(Select.java:828)
at org.h2.command.query.Query.queryWithoutCacheLazyCheck(Query.java:197)
at org.h2.command.query.Query.query(Query.java:520)
at org.h2.command.query.Query.query(Query.java:483)
at org.h2.command.CommandContainer.query(CommandContainer.java:252)
at org.h2.command.Command.executeQuery(Command.java:192)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:257)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:31:28.088309+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U.LOGIN" должен быть в предложении GROUP BY
Column "U.LOGIN" must be in the GROUP BY list; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id [90016-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.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.updateAggregate(ExpressionColumn.java:266)
at org.h2.expression.Alias.updateAggregate(Alias.java:74)
at org.h2.command.query.Select.updateAgg(Select.java:539)
at org.h2.command.query.Select.gatherGroup(Select.java:522)
at org.h2.command.query.Select.queryGroup(Select.java:488)
at org.h2.command.query.Select.queryWithoutCache(Select.java:828)
at org.h2.command.query.Query.queryWithoutCacheLazyCheck(Query.java:197)
at org.h2.command.query.Query.query(Query.java:520)
at org.h2.command.query.Query.query(Query.java:483)
at org.h2.command.CommandContainer.query(CommandContainer.java:252)
at org.h2.command.Command.executeQuery(Command.java:192)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:257)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:35:53.107821+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]dsc"
Syntax error in SQL statement "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]dsc"; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count dsc [42000-224]
2024-04-18 18:36:21.300704+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DSC"
Syntax error in SQL statement "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DSC"; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count DSC [42000-224]
2024-04-18 18:36:41.364562+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DES"
Syntax error in SQL statement "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DES"; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count DES [42000-224]
2024-04-18 18:41:46.400938+04:00 database: wrong user or password; user: "SA"
org.h2.message.DbException: Неверное имя пользователя или пароль
Wrong user name or password [28000-224]
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.message.DbException.get(DbException.java:188)
at org.h2.engine.Engine.openSession(Engine.java:154)
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.util.JdbcUtils.getConnection(JdbcUtils.java:288)
at org.h2.server.web.WebServer.getConnection(WebServer.java:811)
at org.h2.server.web.WebApp.login(WebApp.java:1039)
at org.h2.server.web.WebApp.process(WebApp.java:227)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
Wrong user name or password [28000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:522)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 50 more
2024-04-18 18:42:06.702323+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U" не найден
Column "U" not found; SQL statement:
SELECT u as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.Alias.optimize(Alias.java:52)
at org.h2.command.query.Select.prepareExpressions(Select.java:1170)
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.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:43:02.191025+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U" не найден
Column "U" not found; SQL statement:
SELECT u as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.Alias.optimize(Alias.java:52)
at org.h2.command.query.Select.prepareExpressions(Select.java:1170)
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.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java: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:340)
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:61)
at java.base/java.lang.Thread.run(Thread.java:1583)

View File

@ -2,8 +2,13 @@ package ip_2.lab1;
import ip_2.lab1.items.model.ItemEntity; import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.service.ItemService; import ip_2.lab1.items.service.ItemService;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.service.ReviewService;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService; import ip_2.lab1.types.service.TypeService;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.h2.engine.User;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
@ -18,10 +23,14 @@ public class Lab1Application implements CommandLineRunner {
private final TypeService typeService; private final TypeService typeService;
private final ItemService itemService; private final ItemService itemService;
private final UserService userService;
private final ReviewService reviewService;
public Lab1Application(TypeService typeService, ItemService itemService) { public Lab1Application(TypeService typeService, ItemService itemService, UserService userService, ReviewService reviewService) {
this.typeService = typeService; this.typeService = typeService;
this.itemService = itemService; this.itemService = itemService;
this.userService = userService;
this.reviewService = reviewService;
} }
public static void main(String[] args) { public static void main(String[] args) {
@ -32,18 +41,36 @@ public class Lab1Application implements CommandLineRunner {
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) { if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default types values"); log.info("Create default types values");
final var type1 = typeService.create(new TypeEntity(null, "Асфальт", 2000)); final var type1 = typeService.create(new TypeEntity("Асфальт", 2000));
final var type2 = typeService.create(new TypeEntity(null, "Грунт", 3000)); final var type2 = typeService.create(new TypeEntity("Грунт", 3000));
final var type3 = typeService.create(new TypeEntity(null, "Асфальт + грунт", 3500)); final var type3 = typeService.create(new TypeEntity("Асфальт + грунт", 3500));
log.info("Create default items values"); log.info("Create items");
itemService.create(new ItemEntity(null, type1, 49999, 20)); final var item1 = itemService.create(new ItemEntity(type1, 1700, 5));
itemService.create(new ItemEntity(null, type1, 129999, 3)); final var item2 = itemService.create(new ItemEntity(type2, 2700, 5));
itemService.create(new ItemEntity(null, type2, 15450, 30)); final var item3 = itemService.create(new ItemEntity(type3, 3200, 5));
itemService.create(new ItemEntity(null, type2, 69900, 10));
itemService.create(new ItemEntity(null, type2, 150000, 6)); log.info("Create users");
itemService.create(new ItemEntity(null, type3, 75000, 6)); final var user1 = userService.create(new UserEntity("Artyom", "1234"));
itemService.create(new ItemEntity(null, type3, 67800, 3)); final var user2 = userService.create(new UserEntity("Niyaz", "1234"));
final var user3 = userService.create(new UserEntity("Rostik", "1234"));
final var user4 = userService.create(new UserEntity("Artur", "1234"));
final var user5 = userService.create(new UserEntity("Andrey", "1234"));
final var user6 = userService.create(new UserEntity("Alionchik", "1234"));
log.info("Create reviews");
final var review1 = reviewService.create(new ReviewEntity(user1, "Кайфарики"));
final var review2 = reviewService.create(new ReviewEntity(user2, "Кайфарики кайфецкие"));
final var review3 = reviewService.create(new ReviewEntity(user3, "Кайфарики турецкие"));
final var review4 = reviewService.create(new ReviewEntity(user3, "Кайфарики масдавские"));
final var review5 = reviewService.create(new ReviewEntity(user4, "Кайфарики минские"));
final var review7 = reviewService.create(new ReviewEntity(user4, "Кайфарики грузинские"));
final var review8 = reviewService.create(new ReviewEntity(user5, "Кайфарики японские"));
final var review9 = reviewService.create(new ReviewEntity(user6, "Кайфарики македонские"));
log.info("Creation finished");
} }
} }
} }

View File

@ -0,0 +1,97 @@
package ip_2.lab1.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 ip_2.lab1.core.api;
import org.springframework.data.domain.Page;
import java.util.function.Function;
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,6 +1,8 @@
package ip_2.lab1.core.configuration; package ip_2.lab1.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";
private Constants(){ private Constants(){

View File

@ -1,7 +1,7 @@
package ip_2.lab1.core.error; package ip_2.lab1.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,18 @@
package ip_2.lab1.core.model; package ip_2.lab1.core.model;
import com.fasterxml.jackson.databind.ser.Serializers; import com.fasterxml.jackson.databind.ser.Serializers;
import ip_2.lab1.core.configuration.Constants;
import jakarta.persistence.*;
@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,13 +0,0 @@
package ip_2.lab1.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,55 +0,0 @@
package ip_2.lab1.core.repository;
import ip_2.lab1.core.model.BaseEntity;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
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

@ -2,6 +2,7 @@ package ip_2.lab1.items.api;
import ip_2.lab1.core.configuration.Constants; import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.items.model.ItemEntity; import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.items.service.ItemService; import ip_2.lab1.items.service.ItemService;
import ip_2.lab1.types.service.TypeService; import ip_2.lab1.types.service.TypeService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@ -36,6 +37,10 @@ public class ItemController {
entity.setType(typeService.get(dto.getTypeId())); entity.setType(typeService.get(dto.getTypeId()));
return entity; return entity;
} }
private ItemGroupedDto toGroupedDto(ItemGrouped entity) {
return modelMapper.map(entity, ItemGroupedDto.class);
}
@GetMapping @GetMapping
public List<ItemDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId) { public List<ItemDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId) {
@ -48,7 +53,8 @@ public class ItemController {
} }
@PostMapping @PostMapping
public ItemDto create(@RequestBody ItemDto dto) { public ItemDto create(
@RequestBody ItemDto dto) {
return toDto(itemService.create( toEntity(dto))); return toDto(itemService.create( toEntity(dto)));
} }
@ -61,4 +67,11 @@ public class ItemController {
public ItemDto delete(@PathVariable(name = "id") Long id) { public ItemDto delete(@PathVariable(name = "id") Long id) {
return toDto(itemService.delete(id)); return toDto(itemService.delete(id));
} }
@GetMapping("/total")
public List<ItemGroupedDto> getTotalPrice() {
return itemService.getTotal().stream()
.map(this::toGroupedDto)
.toList();
}
} }

View File

@ -9,6 +9,7 @@ import jakarta.validation.constraints.NotNull;
import java.util.Objects; import java.util.Objects;
public class ItemDto { public class ItemDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1) @Min(1)
@ -22,7 +23,6 @@ public class ItemDto {
private Double benefit; private Double benefit;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -0,0 +1,22 @@
package ip_2.lab1.items.api;
public class ItemGroupedDto {
private Long typeId;
private Integer totalPrice;
public Long getTypeId() {
return typeId;
}
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}

View File

@ -3,20 +3,25 @@ package ip_2.lab1.items.model;
import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.security.SecurityScheme;
import ip_2.lab1.core.model.BaseEntity; import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import jakarta.persistence.*;
import java.util.Objects; import java.util.Objects;
@Entity
@Table(name = "items")
public class ItemEntity extends BaseEntity { public class ItemEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type; private TypeEntity type;
@Column(nullable = false)
private Integer price; private Integer price;
@Column(nullable = false)
private Integer count; private Integer count;
public ItemEntity() { public ItemEntity() {
super();
} }
public ItemEntity(Long id, TypeEntity type, Integer price, Integer count) { public ItemEntity(TypeEntity type, Integer price, Integer count) {
super(id);
this.type = type; this.type = type;
this.price = price; this.price = price;
this.count = count; this.count = count;

View File

@ -0,0 +1,8 @@
package ip_2.lab1.items.model;
import ip_2.lab1.types.model.TypeEntity;
public interface ItemGrouped {
TypeEntity getType();
int getTotalPrice();
}

View File

@ -1,9 +1,17 @@
package ip_2.lab1.items.repository; package ip_2.lab1.items.repository;
import ip_2.lab1.core.repository.MapRepository;
import ip_2.lab1.items.model.ItemEntity; import ip_2.lab1.items.model.ItemEntity;
import org.springframework.stereotype.Repository; import ip_2.lab1.items.model.ItemGrouped;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
@Repository public interface ItemRepository extends CrudRepository<ItemEntity, Long> {
public class ItemRepository extends MapRepository<ItemEntity> { List<ItemEntity> findByTypeId(long typeId);
void deleteAllByTypeId(Long typeId);
@Query("select t as type, coalesce(sum(i.price * i.count), 0) as totalPrice "
+ "from TypeEntity t left join ItemEntity i on i.type = t "
+ "group by t order by t.id")
List<ItemGrouped> getItemsTotalByType();
} }

View File

@ -2,12 +2,17 @@ package ip_2.lab1.items.service;
import ip_2.lab1.core.error.NotFoundException; import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.model.ItemEntity; import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.items.repository.ItemRepository; import ip_2.lab1.items.repository.ItemRepository;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService;
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.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.stream.StreamSupport;
@Service @Service
public class ItemService { public class ItemService {
@ -17,33 +22,47 @@ public class ItemService {
this.repository = repository; this.repository = repository;
} }
public List<ItemEntity> getAll(Long typeId) { @Transactional(readOnly = true)
if (Objects.equals(typeId, 0L)) { public List<ItemEntity> getAll(long typeId) {
return repository.getAll(); if (typeId <= 0L) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} else {
return repository.findByTypeId(typeId);
} }
return repository.getAll().stream()
.filter(item -> item.getType().getId().equals(typeId)).toList();
} }
public ItemEntity get(Long id) { @Transactional(readOnly = true)
return Optional.ofNullable(repository.get(id)) public ItemEntity get(long id) {
.orElseThrow(() -> new NotFoundException(id)); return repository.findById(id)
.orElseThrow(() -> new NotFoundException(ItemEntity.class, id));
} }
@Transactional
public ItemEntity create(ItemEntity entity) { public ItemEntity create(ItemEntity entity) {
return repository.create(entity); if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
} }
public ItemEntity update(Long id, ItemEntity entity) { @Transactional
public ItemEntity update(long id, ItemEntity entity) {
final ItemEntity existsEntity = get(id); final ItemEntity existsEntity = get(id);
existsEntity.setType(entity.getType()); existsEntity.setType(entity.getType());
existsEntity.setPrice(entity.getPrice()); existsEntity.setPrice(entity.getPrice());
existsEntity.setCount(entity.getCount()); existsEntity.setCount(entity.getCount());
return repository.update(existsEntity); return repository.save(existsEntity);
} }
public ItemEntity delete(Long id) { @Transactional
public ItemEntity delete(long id) {
final ItemEntity existsEntity = get(id); final ItemEntity existsEntity = get(id);
return repository.delete(existsEntity); repository.delete(existsEntity);
return existsEntity;
}
@Transactional(readOnly = true)
public List<ItemGrouped> getTotal() {
return repository.getItemsTotalByType();
} }
} }

View File

@ -1,24 +1,38 @@
package ip_2.lab1.reviews.api; package ip_2.lab1.reviews.api;
import ip_2.lab1.core.api.PageDto;
import ip_2.lab1.core.api.PageDtoMapper;
import ip_2.lab1.core.configuration.Constants; import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.items.api.ItemGroupedDto;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.reviews.model.ReviewEntity; import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.model.ReviewGrouped;
import ip_2.lab1.reviews.repository.ReviewRepository;
import ip_2.lab1.reviews.service.ReviewService; import ip_2.lab1.reviews.service.ReviewService;
import ip_2.lab1.types.api.TypeDto; import ip_2.lab1.users.service.UserService;
import ip_2.lab1.types.model.TypeEntity; import jakarta.validation.constraints.Max;
import ip_2.lab1.types.service.TypeService; import jakarta.validation.constraints.Min;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
import java.util.stream.StreamSupport;
@RestController @RestController
@RequestMapping(Constants.API_URL + "/review") @RequestMapping(Constants.API_URL + "/review")
public class ReviewController { public class ReviewController {
private final UserService userService;
private final ReviewService reviewService; private final ReviewService reviewService;
private final ReviewRepository reviewRepository;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
public ReviewController(ReviewService reviewService, ModelMapper modelMapper) { public ReviewController(UserService userService, ReviewService reviewService, ReviewRepository reviewRepository, ModelMapper modelMapper) {
this.userService = userService;
this.reviewService = reviewService; this.reviewService = reviewService;
this.reviewRepository = reviewRepository;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
} }
@ -26,12 +40,19 @@ public class ReviewController {
return modelMapper.map(entity, ReviewDto.class); return modelMapper.map(entity, ReviewDto.class);
} }
private ReviewEntity toEntity(ReviewDto dto) { private ReviewEntity toEntity(ReviewDto dto) {
return modelMapper.map(dto, ReviewEntity.class); final ReviewEntity entity = modelMapper.map(dto, ReviewEntity.class);
entity.setUser(userService.getForReviewCreate(dto.getUserId()));
return entity;
}
private ReviewGroupedDto toGroupedDto(ReviewGrouped entity) {
return modelMapper.map(entity, ReviewGroupedDto.class);
} }
@GetMapping @GetMapping
public List<ReviewDto> getAll() { public PageDto<ReviewDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Long userId,
return reviewService.getAll().stream().map(this::toDto).toList(); @RequestParam(name = "page", defaultValue = "0") Integer page,
@RequestParam(name = "size", defaultValue = "20") Integer size) {
return PageDtoMapper.toDto(reviewService.getAll(userId, page, size), this::toDto);
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@ -53,4 +74,9 @@ public class ReviewController {
public ReviewDto delete(@PathVariable(name = "id") Long id) { public ReviewDto delete(@PathVariable(name = "id") Long id) {
return toDto(reviewService.delete(id)); return toDto(reviewService.delete(id));
} }
@GetMapping("/count")
public List<ReviewGroupedDto> getReviewCount() {
return reviewService.getCount(0, 5).stream().map(this::toGroupedDto).toList();
}
} }

View File

@ -4,15 +4,18 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class ReviewDto { public class ReviewDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull
@Min(1)
private Long userId;
@NotBlank @NotBlank
private String name; @Size(min = 3, max = 300)
@NotBlank
private String text; private String text;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { public Long getId() {
return id; return id;
} }
@ -20,11 +23,11 @@ public class ReviewDto {
this.id = id; this.id = id;
} }
public String getName() { public Long getUserId() {
return name; return userId;
} }
public void setName(String name) { public void setUserId(Long userId) {
this.name = name; this.userId = userId;
} }
public String getText() { return text; } public String getText() { return text; }

View File

@ -0,0 +1,22 @@
package ip_2.lab1.reviews.api;
public class ReviewGroupedDto {
private String userLogin;
private Integer count;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
}

View File

@ -2,29 +2,36 @@ package ip_2.lab1.reviews.model;
import ip_2.lab1.core.model.BaseEntity; import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.users.model.UserEntity;
import jakarta.persistence.*;
import org.h2.engine.User;
import org.hibernate.annotations.Cascade;
import java.util.Objects; import java.util.Objects;
@Entity
@Table(name = "reviews")
public class ReviewEntity extends BaseEntity { public class ReviewEntity extends BaseEntity {
private String name; @ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Column(nullable = false, length = 300)
private String text; private String text;
public ReviewEntity() { public ReviewEntity() {
super();
} }
public ReviewEntity(Long id, String name, String text) { public ReviewEntity(UserEntity user, String text) {
super(id); this.user = user;
this.name = name;
this.text = text; this.text = text;
} }
public String getName() { public UserEntity getUser() { return user;}
return name; public void setUser(UserEntity user) {
this.user = user;
if(!user.getReviews().contains(this))
user.addReview(this);
} }
public void setName(String name) {
this.name = name;
}
public String getText() { public String getText() {
return text; return text;
} }
@ -34,7 +41,7 @@ public class ReviewEntity extends BaseEntity {
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, name, text); return Objects.hash(id, user, text);
} }
@Override @Override
@ -44,7 +51,7 @@ public class ReviewEntity extends BaseEntity {
if (obj == null || getClass() != obj.getClass()) if (obj == null || getClass() != obj.getClass())
return false; return false;
final ReviewEntity other = (ReviewEntity) obj; final ReviewEntity other = (ReviewEntity) obj;
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name) return Objects.equals(other.getId(), id) && Objects.equals(other.getUser().getId(), user.getId())
&& Objects.equals(other.getText(), text); && Objects.equals(other.getText(), text);
} }
} }

View File

@ -0,0 +1,8 @@
package ip_2.lab1.reviews.model;
import ip_2.lab1.users.model.UserEntity;
public interface ReviewGrouped {
UserEntity getUser();
Integer getCount();
}

View File

@ -1,9 +1,22 @@
package ip_2.lab1.reviews.repository; package ip_2.lab1.reviews.repository;
import ip_2.lab1.core.repository.MapRepository;
import ip_2.lab1.reviews.model.ReviewEntity; import ip_2.lab1.reviews.model.ReviewEntity;
import org.springframework.stereotype.Repository; import ip_2.lab1.reviews.model.ReviewGrouped;
import ip_2.lab1.users.model.UserEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface ReviewRepository extends CrudRepository<ReviewEntity, Long>, PagingAndSortingRepository<ReviewEntity, Long> {
Page<ReviewEntity> findByUserId(Long userId, Pageable pageable);
List<ReviewEntity> findByUserId(Long userId);
void deleteAllByUserId(Long userId);
@Query("SELECT u as user, count(*) as count FROM ReviewEntity r join UserEntity u on u = r.user group by user order by count DESC ")
Page<ReviewGrouped> getReviewCountByUsers(Pageable pageable);
@Repository
public class ReviewRepository extends MapRepository<ReviewEntity> {
} }

View File

@ -1,44 +1,86 @@
package ip_2.lab1.reviews.service; package ip_2.lab1.reviews.service;
import ip_2.lab1.core.error.NotFoundException; import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.reviews.model.ReviewEntity; import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.model.ReviewGrouped;
import ip_2.lab1.reviews.repository.ReviewRepository; import ip_2.lab1.reviews.repository.ReviewRepository;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.repository.TypeRepository; import ip_2.lab1.types.repository.TypeRepository;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.antlr.v4.runtime.atn.SemanticContext;
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.web.bind.annotation.RequestParam;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.StreamSupport;
@Service @Service
public class ReviewService { public class ReviewService {
private final ReviewRepository repository; private final ReviewRepository repository;
private final UserService userService;
public ReviewService(ReviewRepository repository) { public ReviewService(ReviewRepository repository, UserService userService) {
this.repository = repository; this.repository = repository;
this.userService = userService;
} }
public List<ReviewEntity> getAll() { @Transactional(readOnly = true)
return repository.getAll(); public List<ReviewEntity> getAll(long userId) {
if (userId <= 0L)
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
userService.get(userId);
return repository.findByUserId(userId);
} }
@Transactional(readOnly = true)
public Page<ReviewEntity> getAll(long userId, Integer offset, Integer limit) {
if (userId <= 0L)
return repository.findAll(PageRequest.of(offset, limit));
userService.get(userId);
return repository.findByUserId(userId, PageRequest.of(offset, limit));
}
@Transactional(readOnly = true)
public ReviewEntity get(Long id) { public ReviewEntity get(Long id) {
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id)); return repository.findById(id).orElseThrow(() -> new NotFoundException(ReviewEntity.class, id));
} }
@Transactional
public ReviewEntity create(ReviewEntity entity) { public ReviewEntity create(ReviewEntity entity) {
return repository.create(entity); if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
final UserEntity existUser = userService.get(entity.getUser().getId());
entity.setUser(existUser);
return repository.save(entity);
} }
public ReviewEntity update(Long id, ReviewEntity entity) { @Transactional
public ReviewEntity update(long id, ReviewEntity entity) {
final ReviewEntity existsEntity = get(id); final ReviewEntity existsEntity = get(id);
existsEntity.setName(entity.getName()); userService.get(entity.getUser().getId());
existsEntity.setUser(entity.getUser());
existsEntity.setText(entity.getText()); existsEntity.setText(entity.getText());
return repository.update(existsEntity); return repository.save(existsEntity);
} }
public ReviewEntity delete(Long id) { @Transactional
public ReviewEntity delete(long id) {
final ReviewEntity existsEntity = get(id); final ReviewEntity existsEntity = get(id);
return repository.delete(existsEntity); repository.delete(existsEntity);
return existsEntity;
}
@Transactional(readOnly = true)
public Page<ReviewGrouped> getCount(int offset, int limit) {
return repository.getReviewCountByUsers(PageRequest.of(offset, limit));
} }
} }

View File

@ -3,7 +3,6 @@ package ip_2.lab1.types.api;
import ip_2.lab1.core.configuration.Constants; import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService; import ip_2.lab1.types.service.TypeService;
import jakarta.validation.Valid;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;

View File

@ -2,19 +2,19 @@ package ip_2.lab1.types.api;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class TypeDto { public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotBlank @NotBlank
@Size(min = 3, max = 30)
private String name; private String name;
@NotNull @NotNull
@Min(1) @Min(1)
@Size(min = 1, max = 10)
private Integer basePrice; private Integer basePrice;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -1,19 +1,25 @@
package ip_2.lab1.types.model; package ip_2.lab1.types.model;
import ip_2.lab1.core.model.BaseEntity; import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.items.model.ItemEntity;
import jakarta.persistence.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "types")
public class TypeEntity extends BaseEntity { public class TypeEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 30)
private String name; private String name;
@Column(nullable = false, length = 10)
private Integer basePrice; private Integer basePrice;
public TypeEntity() { public TypeEntity() {
super();
} }
public TypeEntity(Long id, String name, Integer basePrice) { public TypeEntity(String name, Integer basePrice) {
super(id);
this.name = name; this.name = name;
this.basePrice = basePrice; this.basePrice = basePrice;
} }

View File

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

View File

@ -1,47 +1,64 @@
package ip_2.lab1.types.service; package ip_2.lab1.types.service;
import ip_2.lab1.core.error.NotFoundException; import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.repository.ItemRepository;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.repository.TypeRepository; import ip_2.lab1.types.repository.TypeRepository;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.StreamSupport;
@Service @Service
public class TypeService { public class TypeService {
private final TypeRepository repository; private final TypeRepository repository;
private final ItemRepository itemRepository;
public TypeService(TypeRepository repository) { public TypeService(TypeRepository repository, ItemRepository itemRepository) {
this.repository = repository; this.repository = repository;
this.itemRepository = itemRepository;
} }
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)).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");
} }
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());
existsEntity.setBasePrice(entity.getBasePrice()); existsEntity.setBasePrice(entity.getBasePrice());
return repository.update(existsEntity); return repository.save(existsEntity);
} }
public TypeEntity delete(Long id) { public TypeEntity delete(Long id) {
final TypeEntity existsEntity = get(id); final TypeEntity existsEntity = get(id);
return repository.delete(existsEntity); itemRepository.deleteAllByTypeId(id);
repository.delete(existsEntity);
return existsEntity;
} }
// public void deleteAll() {
// repository.deleteAll();
// }
} }

View File

@ -0,0 +1,48 @@
package ip_2.lab1.users.api;
import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper){
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity){ return modelMapper.map(entity, UserDto.class);}
private UserEntity toEntity(UserDto dto){ return modelMapper.map(dto, UserEntity.class);}
@GetMapping
public List<UserDto> getAll(){ return userService.getAll().stream().map(this::toDto).toList();}
@GetMapping("/{id}")
public UserDto get(@PathVariable(name = "id") Long id){ return toDto(userService.get(id));}
@PostMapping()
public UserDto create(@RequestBody UserDto dto){ return toDto(userService.create(toEntity(dto)));}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto){
return toDto(userService.update(id, toEntity(dto)));
}
@PutMapping("/updatePassword/{id}")
public UserDto updatePassword(@PathVariable(name = "id") Long id, @RequestParam String password){
return toDto(userService.updatePassword(id, password));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id){
return toDto(userService.delete(id));
}
}

View File

@ -0,0 +1,41 @@
package ip_2.lab1.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import ip_2.lab1.reviews.model.ReviewEntity;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.Set;
public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 3, max = 30)
private String login;
@NotBlank
@Size(min = 4, max = 30)
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,68 @@
package ip_2.lab1.users.model;
import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.types.model.TypeEntity;
import jakarta.persistence.*;
import org.h2.engine.User;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private final Set<ReviewEntity> reviews = new HashSet<>();
@Column(nullable = false, unique = true, length = 30)
private String login;
@Column(nullable = false, length = 30)
private String password;
public UserEntity() {
}
public UserEntity (String login, String password){
this.login = login;
this.password = password;
}
public String getLogin(){ return login;}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() { return password; }
public void setPassword(String password) {
this.password = password;
}
public Set<ReviewEntity> getReviews() {
return reviews;
}
public void addReview(ReviewEntity review) {
if (review.getUser() != this) {
review.setUser(this);
}
reviews.add(review);
}
@Override
public int hashCode() {
return Objects.hash(id, login, password);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id) && Objects.equals(other.getLogin(), login)
&& Objects.equals(other.getPassword(), password);
}
}

View File

@ -0,0 +1,14 @@
package ip_2.lab1.users.repository;
import ip_2.lab1.users.model.UserEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<UserEntity, Long> {
Optional<UserEntity> findByLoginIgnoreCase(String login);
@Query("select u from UserEntity u join fetch u.reviews where u.id = ?1")
Optional<UserEntity> findByIdForReviewCreate(Long id);
}

View File

@ -0,0 +1,89 @@
package ip_2.lab1.users.service;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.repository.ReviewRepository;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.StreamSupport;
@Service
public class UserService {
private final UserRepository repository;
private final ReviewRepository reviewRepository;
public UserService(UserRepository repository, ReviewRepository reviewRepository){
this.repository = repository;
this.reviewRepository = reviewRepository;
}
private void checkLogin(String login) {
if (repository.findByLoginIgnoreCase(login).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll(){
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public UserEntity get(Long id){
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional(readOnly = true)
public UserEntity getForReviewCreate(Long id){
return repository.findByIdForReviewCreate(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public UserEntity create(UserEntity entity){
if (entity == null){
throw new IllegalArgumentException("Entity is null");
}
checkLogin(entity.getLogin());
return repository.save(entity);
}
@Transactional
public UserEntity update(Long id, UserEntity entity){
if (entity == null)
throw new IllegalArgumentException("Entity is null");
final UserEntity existsEntity = get(id);
existsEntity.setLogin(entity.getLogin());
return repository.save(existsEntity);
}
@Transactional
public UserEntity updatePassword(Long id, String password){
if (password == null)
throw new IllegalArgumentException("Password is null");
final UserEntity existsEntity = get(id);
if (password.equals(existsEntity.getPassword()))
throw new IllegalArgumentException("It is existing password");
if (password.contains("1234"))
throw new IllegalArgumentException("Password could not contains numeric sequences");
if(password.length() > 30 || password.length() < 4)
throw new IllegalArgumentException("Password`s length must be in range 4 and 30 characters");
existsEntity.setPassword(password);
return repository.save(existsEntity);
}
@Transactional
public UserEntity delete(Long id){
final UserEntity existsEntity = get(id);
reviewRepository.deleteAllByUserId(id);
repository.deleteById(id);
return existsEntity;
}
}

View File

@ -1 +1,20 @@
# Server
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

@ -0,0 +1,88 @@
package ip_2.lab1;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.service.ItemService;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ItemServiceTest {
@Autowired
private ItemService itemService;
@Autowired
private TypeService typeService;
private TypeEntity type;
private ItemEntity item;
private ItemEntity item2;
private ItemEntity item3;
@BeforeEach
void createData(){
removeData();
type = typeService.create(new TypeEntity("Asfalt", 1000));
item = itemService.create(new ItemEntity(type, 900, 10));
item2 = itemService.create(new ItemEntity(type, 800, 5));
item3 = itemService.create(new ItemEntity(type, 700, 100));
}
@AfterEach
void removeData(){
itemService.getAll(0L).forEach(item -> itemService.delete(item.getId()));
typeService.getAll().forEach(type -> typeService.delete(type.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> itemService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, itemService.getAll(0L).size());
Assertions.assertEquals(item, itemService.get(item.getId()));
}
@Test
void createNullableTest() {
final ItemEntity NullableItem = new ItemEntity(null, null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> itemService.create(NullableItem));
}
@Test
void updateTest() {
final int testPrice = 1800;
final int testCount = 20;
final TypeEntity type1 = typeService.create(new TypeEntity("Grunt", 2000));
final TypeEntity oldType = item.getType();
final int oldPrice = item.getPrice();
final int oldCount = item.getCount();
final ItemEntity newEntity = itemService.update(item.getId(), new ItemEntity(type1, testPrice, testCount));
Assertions.assertEquals(3, itemService.getAll(0L).size());
Assertions.assertEquals(newEntity, itemService.get(item.getId()));
Assertions.assertEquals(type1, newEntity.getType());
Assertions.assertEquals(testPrice, newEntity.getPrice());
Assertions.assertEquals(testCount, newEntity.getCount());
Assertions.assertNotEquals(oldType, newEntity.getType());
Assertions.assertNotEquals(oldPrice, newEntity.getPrice());
Assertions.assertNotEquals(oldCount, newEntity.getCount());
}
@Test
void deleteTest() {
itemService.delete(item3.getId());
Assertions.assertEquals(2, itemService.getAll(0L).size());
final ItemEntity last = itemService.get(item2.getId());
Assertions.assertEquals(item2.getId(), last.getId());
}
}

View File

@ -0,0 +1,74 @@
package ip_2.lab1;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.service.ReviewService;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ReviewServiceTest {
@Autowired
private ReviewService reviewService;
@Autowired
private UserService userService;
private UserEntity user;
private ReviewEntity review;
private ReviewEntity review2;
private ReviewEntity review3;
@BeforeEach
void createData(){
removeData();
user = userService.create(new UserEntity("Artyom", "1234"));
review = reviewService.create(new ReviewEntity(user, "Good"));
review2 = reviewService.create(new ReviewEntity(user, "Super good"));
review3 = reviewService.create(new ReviewEntity(user, "Not bad"));
}
@AfterEach
void removeData(){
reviewService.getAll(0L).forEach(review -> reviewService.delete(review.getId()));
userService.getAll().forEach(user -> userService.delete(user.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> reviewService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, reviewService.getAll(0L).size());
Assertions.assertEquals(review, reviewService.get(review.getId()));
}
@Test
void updateTest() {
final String text = "test";
final UserEntity user1 = userService.create(new UserEntity("Niyaz", "1234"));
final UserEntity oldUser = review.getUser();
final String oldText = review.getText();
final ReviewEntity newEntity = reviewService.update(review.getId(), new ReviewEntity(user1, text));
Assertions.assertEquals(3, reviewService.getAll(0L).size());
Assertions.assertEquals(newEntity, reviewService.get(review.getId()));
Assertions.assertEquals(user1, newEntity.getUser());
Assertions.assertEquals(text, newEntity.getText());
Assertions.assertNotEquals(oldUser, newEntity.getUser());
Assertions.assertNotEquals(oldText, newEntity.getText());
}
@Test
void deleteTest() {
reviewService.delete(review3.getId());
Assertions.assertEquals(2, reviewService.getAll(0L).size());
final ReviewEntity last = reviewService.get(review2.getId());
Assertions.assertEquals(review2.getId(), last.getId());
}
}

View File

@ -3,13 +3,11 @@ package ip_2.lab1;
import ip_2.lab1.types.service.TypeService; import ip_2.lab1.types.service.TypeService;
import ip_2.lab1.core.error.NotFoundException; import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.types.model.TypeEntity; import ip_2.lab1.types.model.TypeEntity;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.*;
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.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;
@SpringBootTest @SpringBootTest
@TestMethodOrder(OrderAnnotation.class) @TestMethodOrder(OrderAnnotation.class)
@ -17,47 +15,67 @@ class TypeServiceTests {
@Autowired @Autowired
private TypeService typeService; private TypeService typeService;
private TypeEntity type;
@BeforeEach
void createData() {
removeData();
type = typeService.create(new TypeEntity("Asfalt", 2000));
typeService.create(new TypeEntity("Grunt", 3000));
typeService.create(new TypeEntity("Asfalt + Grunt", 3500));
}
@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, "Asphalt", 2000));
typeService.create(new TypeEntity(null, "Grunt", 3000));
final TypeEntity last = typeService.create(new TypeEntity(null, "Asphalt + grunt", 3500));
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("Asfalt", 2000);
Assertions.assertThrows(IllegalArgumentException.class, () -> typeService.create(nonUniqueType));
}
@Test
void createNullableTest() {
final TypeEntity nullableType = new TypeEntity(null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
} }
@Test @Test
@Order(2)
void updateTest() { void updateTest() {
final String test1 = "TEST"; final String test = "TEST";
final Integer test2 = 1000; final Integer testPrice = 1000;
final TypeEntity entity = typeService.get(3L); final String oldName = type.getName();
final String oldName = entity.getName(); final Integer oldPrice = type.getBasePrice();
final Integer oldPrice = entity.getBasePrice(); final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test, testPrice));
final TypeEntity newEntity = typeService.update(3L, new TypeEntity(1L, test1, test2));
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(test1, newEntity.getName()); Assertions.assertEquals(test, newEntity.getName());
Assertions.assertEquals(test2, newEntity.getBasePrice()); Assertions.assertEquals(testPrice, newEntity.getBasePrice());
Assertions.assertNotEquals(oldName, newEntity.getName()); Assertions.assertNotEquals(oldName, newEntity.getName());
Assertions.assertNotEquals(oldPrice, newEntity.getBasePrice());
} }
@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, "Asphalt + grunt", 3500)); final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName(), type.getBasePrice()));
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

@ -0,0 +1,87 @@
package ip_2.lab1;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserServiceTest {
@Autowired
private UserService userService;
private UserEntity entity;
@BeforeEach
void createData() {
removeData();
entity = userService.create(new UserEntity("Artyom", "1234"));
userService.create(new UserEntity("Niyaz", "1234"));
userService.create(new UserEntity("Rostik", "1234"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(entity, userService.get(entity.getId()));
}
@Test
void createNotUniqueTest() {
final UserEntity nonUniqueEntity = new UserEntity("Artyom", "1234");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueEntity));
}
@Test
void createNullableTest() {
final UserEntity nullableEntity = new UserEntity(null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableEntity));
}
@Test
void updateTest() {
final String login = "TEST";
final String oldLogin = entity.getLogin();
final String oldPassword = entity.getPassword();
final UserEntity newEntity = userService.update(entity.getId(), new UserEntity(login, null));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(entity.getId()));
Assertions.assertEquals(login, newEntity.getLogin());
Assertions.assertNotEquals(oldLogin, newEntity.getLogin());
}
@Test
void updatePasswordTest(){
final String password = "TEST";
final String oldPassword = entity.getPassword();
final UserEntity newEntity = userService.updatePassword(entity.getId(), password);
Assertions.assertEquals(newEntity, userService.get(entity.getId()));
Assertions.assertEquals(password, newEntity.getPassword());
Assertions.assertNotEquals(oldPassword, newEntity.getPassword());
}
@Test
void deleteTest() {
userService.delete(entity.getId());
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity newEntity = userService.create(new UserEntity(entity.getLogin(), entity.getPassword()));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertNotEquals(entity.getId(), newEntity.getId());
}
}