월 17,600원
5개월 할부 시다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결실전! Querydsl
querydsl 테스트시 에러입니다.
<code>17:02:50.381 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]17:02:50.391 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]17:02:50.427 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [study.querydsl.QuerydslBasicTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]17:02:50.439 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [study.querydsl.QuerydslBasicTest], using SpringBootContextLoader17:02:50.443 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [study.querydsl.QuerydslBasicTest]: class path resource [study/querydsl/QuerydslBasicTest-context.xml] does not exist17:02:50.444 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [study.querydsl.QuerydslBasicTest]: class path resource [study/querydsl/QuerydslBasicTestContext.groovy] does not exist17:02:50.444 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [study.querydsl.QuerydslBasicTest]: no resource found for suffixes {-context.xml, Context.groovy}.17:02:50.445 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [study.querydsl.QuerydslBasicTest]: QuerydslBasicTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.17:02:50.482 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [study.querydsl.QuerydslBasicTest]17:02:50.541 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\Users\alita\Desktop\querydsl\querydsl\out\production\classes\study\querydsl\QuerydslApplication.class]17:02:50.542 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration study.querydsl.QuerydslApplication for test class study.querydsl.QuerydslBasicTest17:02:50.646 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [study.querydsl.QuerydslBasicTest]: using defaults.17:02:50.646 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]17:02:50.664 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@3a1dd365, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@395b56bb, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@256f8274, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@68044f4, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@52d239ba, org.springframework.test.context.support.DirtiesContextTestExecutionListener@315f43d5, org.springframework.test.context.transaction.TransactionalTestExecutionListener@68fa0ba8, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6c5945a7, org.springframework.test.context.event.EventPublishingTestExecutionListener@2f05be7f, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@640f11a1, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@5c10f1c3, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@7ac2e39b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@78365cfa, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@64a8c844, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@3f6db3fb]17:02:50.668 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@424fd310 testClass = QuerydslBasicTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@1a45193b testClass = QuerydslBasicTest, locations = '{}', classes = '{class study.querydsl.QuerydslApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@1e13529a, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@93081b6, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@16c069df, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7c3fdb62, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@4d6025c5, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@80ec1f8], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null]. . ____ _ /\\ / ___'_ __ (_)_ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.7.12)2023-06-26 17:02:51.012 INFO 16528 --- [ main] study.querydsl.QuerydslBasicTest : Starting QuerydslBasicTest using Java 11.0.15 on DESKTOP-UKCCBE9 with PID 16528 (started by alita in C:\Users\alita\Desktop\querydsl\querydsl)2023-06-26 17:02:51.013 INFO 16528 --- [ main] study.querydsl.QuerydslBasicTest : No active profile set, falling back to 1 default profile: "default"2023-06-26 17:02:51.530 INFO 16528 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.2023-06-26 17:02:51.544 INFO 16528 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 7 ms. Found 0 JPA repository interfaces.2023-06-26 17:02:52.025 INFO 16528 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]2023-06-26 17:02:52.079 INFO 16528 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.15.Final2023-06-26 17:02:52.234 INFO 16528 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}2023-06-26 17:02:52.480 INFO 16528 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...2023-06-26 17:02:52.647 INFO 16528 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.2023-06-26 17:02:52.678 INFO 16528 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect2023-06-26 17:02:53.242 DEBUG 16528 --- [ main] org.hibernate.SQL : alter table member drop foreign key FKcjte2jn9pvo9ud2hyfgwcja0kHibernate: alter table member drop foreign key FKcjte2jn9pvo9ud2hyfgwcja0k2023-06-26 17:02:53.256 DEBUG 16528 --- [ main] org.hibernate.SQL : drop table if exists helloHibernate: drop table if exists hello2023-06-26 17:02:53.260 DEBUG 16528 --- [ main] org.hibernate.SQL : drop table if exists hibernate_sequenceHibernate: drop table if exists hibernate_sequence2023-06-26 17:02:53.266 DEBUG 16528 --- [ main] org.hibernate.SQL : drop table if exists memberHibernate: drop table if exists member2023-06-26 17:02:53.270 DEBUG 16528 --- [ main] org.hibernate.SQL : drop table if exists teamHibernate: drop table if exists team2023-06-26 17:02:53.275 DEBUG 16528 --- [ main] org.hibernate.SQL : create table hello ( id bigint not null, primary key (id) ) engine=InnoDBHibernate: create table hello ( id bigint not null, primary key (id) ) engine=InnoDB2023-06-26 17:02:53.286 DEBUG 16528 --- [ main] org.hibernate.SQL : create table hibernate_sequence ( next_val bigint ) engine=InnoDBHibernate: create table hibernate_sequence ( next_val bigint ) engine=InnoDB2023-06-26 17:02:53.296 DEBUG 16528 --- [ main] org.hibernate.SQL : insert into hibernate_sequence values ( 1 )Hibernate: insert into hibernate_sequence values ( 1 )2023-06-26 17:02:53.297 DEBUG 16528 --- [ main] org.hibernate.SQL : create table member ( member_id bigint not null, age integer not null, username varchar(255), team_id bigint, primary key (member_id) ) engine=InnoDBHibernate: create table member ( member_id bigint not null, age integer not null, username varchar(255), team_id bigint, primary key (member_id) ) engine=InnoDB2023-06-26 17:02:53.309 DEBUG 16528 --- [ main] org.hibernate.SQL : create table team ( id bigint not null, name varchar(255), primary key (id) ) engine=InnoDBHibernate: create table team ( id bigint not null, name varchar(255), primary key (id) ) engine=InnoDB2023-06-26 17:02:53.317 DEBUG 16528 --- [ main] org.hibernate.SQL : alter table member add constraint FKcjte2jn9pvo9ud2hyfgwcja0k foreign key (team_id) references team (id)Hibernate: alter table member add constraint FKcjte2jn9pvo9ud2hyfgwcja0k foreign key (team_id) references team (id)2023-06-26 17:02:53.342 INFO 16528 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]2023-06-26 17:02:53.351 INFO 16528 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'2023-06-26 17:02:53.538 WARN 16528 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning2023-06-26 17:02:54.098 INFO 16528 --- [ main] study.querydsl.QuerydslBasicTest : Started QuerydslBasicTest in 3.391 seconds (JVM running for 4.357)2023-06-26 17:02:54.207 INFO 16528 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@424fd310 testClass = QuerydslBasicTest, testInstance = study.querydsl.QuerydslBasicTest@4504a4ed, testMethod = startQuerydsl@QuerydslBasicTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@1a45193b testClass = QuerydslBasicTest, locations = '{}', classes = '{class study.querydsl.QuerydslApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@1e13529a, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@93081b6, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@16c069df, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7c3fdb62, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@4d6025c5, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@80ec1f8], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@250e8712]; rollback [true]2023-06-26 17:02:54.308 DEBUG 16528 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update Hibernate: select next_val as id_val from hibernate_sequence for update 2023-06-26 17:02:54.328 DEBUG 16528 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?Hibernate: update hibernate_sequence set next_val= ? where next_val=?2023-06-26 17:02:54.355 DEBUG 16528 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update Hibernate: select next_val as id_val from hibernate_sequence for update 2023-06-26 17:02:54.356 DEBUG 16528 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?Hibernate: update hibernate_sequence set next_val= ? where next_val=?2023-06-26 17:02:54.359 DEBUG 16528 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update Hibernate: select next_val as id_val from hibernate_sequence for update 2023-06-26 17:02:54.359 DEBUG 16528 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?Hibernate: update hibernate_sequence set next_val= ? where next_val=?2023-06-26 17:02:54.362 DEBUG 16528 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update Hibernate: select next_val as id_val from hibernate_sequence for update 2023-06-26 17:02:54.363 DEBUG 16528 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?Hibernate: update hibernate_sequence set next_val= ? where next_val=?2023-06-26 17:02:54.365 DEBUG 16528 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update Hibernate: select next_val as id_val from hibernate_sequence for update 2023-06-26 17:02:54.365 DEBUG 16528 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?Hibernate: update hibernate_sequence set next_val= ? where next_val=?2023-06-26 17:02:54.367 DEBUG 16528 --- [ main] org.hibernate.SQL : select next_val as id_val from hibernate_sequence for update Hibernate: select next_val as id_val from hibernate_sequence for update 2023-06-26 17:02:54.368 DEBUG 16528 --- [ main] org.hibernate.SQL : update hibernate_sequence set next_val= ? where next_val=?Hibernate: update hibernate_sequence set next_val= ? where next_val=?2023-06-26 17:02:54.409 INFO 16528 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@424fd310 testClass = QuerydslBasicTest, testInstance = study.querydsl.QuerydslBasicTest@4504a4ed, testMethod = startQuerydsl@QuerydslBasicTest, testException = java.lang.NullPointerException, mergedContextConfiguration = [WebMergedContextConfiguration@1a45193b testClass = QuerydslBasicTest, locations = '{}', classes = '{class study.querydsl.QuerydslApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@1e13529a, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@93081b6, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@16c069df, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@7c3fdb62, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@4d6025c5, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@80ec1f8], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]java.lang.NullPointerException at study.querydsl.QuerydslBasicTest.startQuerydsl(QuerydslBasicTest.java:57) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725) at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131) at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140) at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84) at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115) at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105) at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45) at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86) at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86) at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57) at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)2023-06-26 17:02:54.428 INFO 16528 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'2023-06-26 17:02:54.430 INFO 16528 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...2023-06-26 17:02:54.443 INFO 16528 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.Process finished with exit code -1 </code>[질문 내용]QType 활용 2:22초에서 강사님처럼 리팩토링 후 코드 실행시 NullPointer Exception이 발생합니다. 구글 파일 링크입니다.https://drive.google.com/drive/folders/1FxQskkAngeLJcGPtmKUoj-XCmnxm0MVa?usp=sharing
- 미해결실전! Querydsl
빌드 디렉토리에 리포지토리를 생성한 이유에 대해서 구체적으로 궁금합니다.
src main java study에 만들어도 순수JPA 리포지토리로 사용할 수 있는거 아닌가해서요?여태껏 src 패키지에 리포지토리를 한번도 생성하지 않았는데 갑자기 빌드파일에 생성하니까 어떤 이유에서 구체적으로 설명좀 부탁합니다.예를들면 일반 Application.java 파일이 들어있는 src 경로에 생성하면 순수 JPA 리포지토리가 아니라던지?다른분이 질문남겼던거 보긴 했는데 뭔; 공식서포터즈가 강의를 초반에 보면 이유가 나온다고 하는데 강의를 보면 김영한님은 빌드 디렉토리에 생성하는 이유 자체를 구체적으로 언급하지 않던데요?
- 미해결실전! Querydsl
p6spy 쿼리 파라미터 노출 안됨
안녕하세요!이번에 spring boot 3.1.0 version 으로 p6spy 라이브러리 설정 후 테스트 코드 실행을 하는데 쿼리 파라미터 값이 확인되지 않습니다.Hibernate: insert into hello values ( ) 2023-06-20T14:55:04.965+09:00 INFO 28956 --- [ main] p6spy : #1687240504965 | took 5ms | statement | connection 1| url jdbc:mysql://20.249.79.13:3306/patron_dev?characterEncoding=UTF-8 insert into hello values ( ) insert into hello values ( ); Hibernate: select h1_0.id from hello h1_0 2023-06-20T14:55:05.596+09:00 INFO 28956 --- [ main] p6spy : #1687240505596 | took 7ms | statement | connection 1| url jdbc:mysql://20.249.79.13:3306/patron_dev?characterEncoding=UTF-8 select h1_0.id from hello h1_0 select h1_0.id from hello h1_0; 2023-06-20T14:55:05.717+09:00 INFO 28956 --- [ main] p6spy : #1687240505717 | took 9ms | rollback | connection 1| url jdbc:mysql://20.249.79.13:3306/patron_dev?characterEncoding=UTF-8 ; 2023-06-20T14:55:05.759+09:00 INFO 28956 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2023-06-20T14:55:05.763+09:00 INFO 28956 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2023-06-20T14:55:05.849+09:00 INFO 28956 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. Process finished with exit code 0 위 로그 화면에서 보는 것처럼 rollback 이 되기전 insert 문이 실행될 때 값이 비어 있는 상태로 전달되고 있습니다이유를 모르겠습니다 ㅠㅠ
- 미해결실전! Querydsl
JPQL 실행직전 flush외에 clear도 함께 해주는것인지
자바 ORM 표준 JPA프로그램 듣고 넘어왔습니다.이전 기본강의에서는 JPQL이 flush를 먼저 수행이 된후 JPQL쿼리가 동작한다고 배웠는데요.이게 EntityManager의 일반적인 find() 메소드의 경우clear()을 한 뒤 준영속상태에서 비로서 select쿼리가 나가는것으로 알고있습니다. (그렇지 않으면 1차 캐시에서 조회)근데 JPQL의 경우 flush는 자동으로 호출 되지만 clear 즉, 1차캐시와 연관성이 있느냐 없느냐에 대해서 궁금증이 생겼습니다.clear를 직접 해주지 않았음에도 불구하고 쿼리가 나가는 이유에 대해서 clear를 자동으로 해줘서 쿼리가 나가게 된것인지? 혹은 1차 캐시와 상관없이 자연쿼리가 나가게 되는것인지 한번 더 다잡고 가고싶습니다.답변 감사히 기다리겠습니다.
- 해결됨실전! Querydsl
sequence id값이 공유(?)되는 현상에 대한 질문
@GeneratedValue에 의해 Sequence가 호출되어서 순차값이 id에 부여되어 저장되는것으로 알고있습니다.근데, team의 id와 member의 id의 sequence가 마치 공유가 되는듯이 team의 id가 1, 2 그리고 member의 id가 3, 4, 5, 6 으로 저장이 되는 부분에 대해서@Column으로 각각의 id 이름을 다르게 부여했다고 하더라도 @GeneratedValue 어노테이션은 엔티티에 정의한 필드명에 맞춰서 생성이 되어서 그런것인지 궁금합니다.또한, 만약 위 원리가 맞다면 실무에서는 이런 부분에 대해서 각각을 명확하게 구분지어서 해야할거같다 라는 생각이 들었으며,그렇다면 실무에서는 애초에 @Column에 의한 DB 컬럼명 변경이 아닌 엔티티 자체의 필드명에서 부터 다르게 지정해 줘야 하는것이 아닐까 하는 생각을 해봤습니다.이 부분에 대해 바람직하게 생각한것이 맞을까요?
- 미해결실전! Querydsl
PostgreSQL JDBC and json 타입 column 데이터 save
DB mysql 에서는 잘 동작하던 것이 DB 변경할 일이 생겨, mysql -> postgresql 로 전환하였습니다.데이터 insert 시 json 타입 때문에 발생한 에러인데.. 어떻게 조치하면 좋을지 모르겠습니다.SchedulingTask 엔티티@Entity @Getter @Setter @NoArgsConstructor @Slf4j public class SchedulingTask { @Id @Column(name = "task_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(columnDefinition = "jsonb") private String requestBodyString; }저장 하는 코드 public SchedulingTask save(Dbaas dbaas, int priority, ReqInfo reqInfo, String requestBodyString) { log.info("requestBodyString : {}", requestBodyString); SchedulingTask schedulingTask = reqInfo2SchedulingTaskMapper.to(reqInfo, requestBodyString, priority, dbaas); log.info("schedulingTask : {}", schedulingTask.getRequestBodyString()); return schedulingTaskRepository.save(schedulingTask); } log2023-06-20T10:19:10.064+09:00 INFO 15806 --- [nio-8087-exec-1] c.k.c.a.s.t.SchedulingTaskTxService : requestBodyString : {"parameter_group_id":"86dc6f7f-75c5-48a2-b0c6-5e07d5c54f5a","request_type":"scheduled instant","reservation_date_time":"2023-09-30 15:02:00"} 2023-06-20T10:19:10.068+09:00 INFO 15806 --- [nio-8087-exec-1] c.k.c.a.s.t.SchedulingTaskTxService : schedulingTask : {"parameter_group_id":"86dc6f7f-75c5-48a2-b0c6-5e07d5c54f5a","request_type":"scheduled instant","reservation_date_time":"2023-09-30 15:02:00"} 2023-06-20T10:19:10.111+09:00 WARN 15806 --- [nio-8087-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42804 2023-06-20T10:19:10.111+09:00 ERROR 15806 --- [nio-8087-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: column "request_body_string" is of type jsonb but expression is of type character varying Hint: You will need to rewrite or cast the expression. Position: 359 repository 에 직접 저장 시, requestBodyString 을 json 으로 직접 바꿔줘야 하나요??
- 미해결실전! Querydsl
querydsl에서 공통 컬럼 조회 질문 있습니다.
모든 Entity는 createdBy(데이터 작성자) 속성을 갖고 있는 BaseEntity 클래스를 상속하고 있습니다. loginId로 createdBy 속성 값과 loginId가 같은 데이터를 가져오는 메소드를 만들고 싶습니다. 이 메소드를 entity마다 전부 만들어줘야할까요? 아래 코드처럼 처리하면 될 줄 알았는데 이렇게 처리하면 에러가 발생하네요ㅜ 방법이 없을까요?public List<Product> getList(String loginId) { List<Product> products = queryFactory.selectFrom(product) .where(QBaseEntity.baseEntity.createdBy.eq(loginId)) .fetch(); return products; }
- 미해결실전! Querydsl
Page 대신 별도로 구현한 객체를 넘겨주고 있는데 문제가 되는 부분이 있을까요?
안녕하세요~page number가 0부터 시작하는 부분과 Page 자체에 너무 많은 정보가 있는 것 같아 필요한 값만 정의해둔 Dto를 response로 반환해주고 있습니다. (request도 별도로 정의한 dto 객체로 받고 있습니다.)그런데 강의에서 Page 자체를 Response로 반환해주는 것을 보고 현재 제가 하고 있는 방식대로 하면 문제가 될 부분이 있을 지 걱정이 되더라구요..혹시 주의해야하는 부분이 있을지, 이렇게 별도의 객체로 가공해서 넘겨줘도 문제가 없을지 걱정되어 질문드립니다. 😭감사합니다.
- 미해결실전! Querydsl
혹시 join 자체도 특정 조건에 따라 동적으로 작용되게 할 수 있나요?
안녕하세요.where 조건을 동적으로 생성해주는 부분에 대해서는 충분히 이해가 되었습니다.그런데 혹시 특정 condition 값에 따라 join을 해줘야하는 테이블이 다른 경우라면 어떻게 처리되어야 할지 모르겠어서 글을 남기게 되었습니다.condition조건에 teamName이 있을 때만 team을 조인해주고 싶은데 join 구문을 동적으로 처리할 수 있는 좋은 방법이 어떤 것인지 질문드립니다. 😭감사합니다.
- 해결됨실전! Querydsl
순수 jpa 와 queryDsl 실전 관련 오류
아래와 같이 작성했는데 memberJpaRepository. searchWhere() 메서드 호출이 안되네요 ..ㅠㅠ 코드가 문제일까요? @Repository //@RequiredArgsConstructor public class MemberJpaRepository { private final EntityManager em; private final JPAQueryFactory jpaQueryFactory; // 순수 jpa 와 QueryDsl 적용 전 준비 public MemberJpaRepository(EntityManager em) { this.em = em; this.jpaQueryFactory = new JPAQueryFactory(em); } List<MemberTeamDto> searchByBuilder(MemberSearchCond condition){ // BooleanBuilder 동적쿼리 BooleanBuilder builder = new BooleanBuilder(); //StringUtils.hasTest() import stirng.framework -> null, "" 값에 대한 boolean 값 반환 if(hasText(condition.getUsername())){ builder.and(member.username.eq(condition.getUsername())); } if(hasText(condition.getTeamName())){ builder.and(team.name.eq(condition.getTeamName())); } //age 는 null 값 허용 if (condition.getAgeGoe() != null) { builder.and(member.age.goe(condition.getAgeGoe())); } if(condition.getAgeLoe() != null){ builder.and(member.age.loe(condition.getAgeLoe())); } return jpaQueryFactory .select (Projections.constructor( MemberTeamDto.class, member.id, member.username, member.age, team.id, team.name)) .from(member) .leftJoin(member.team,team) .where(builder) .fetch(); } List<MemberTeamDto> searchByWhere(MemberSearchCond condition){ return jpaQueryFactory .select(Projections.constructor(MemberTeamDto.class, member.id, member.username, member.age, team.id, team.name)) .from(member) .leftJoin(member.team, team) .where( usernameEq(condition.getUsername()), teamNameEq(condition.getTeamName()), ageGoe(condition.getAgeLoe()), ageLoe(condition.getAgeLoe()) ).fetch(); } private BooleanExpression usernameEq(String username){ return StringUtils.hasText(username) ? member.username.eq(username): null; } private BooleanExpression teamNameEq(String teamName){ return StringUtils.hasText(teamName) ? team.name.eq(teamName): null; } private BooleanExpression ageGoe(Integer ageGoe){ return ageGoe!= null ? member.age.goe(ageGoe): null; } private BooleanExpression ageLoe(Integer ageLoe){ return ageLoe != null ? member.age.loe(ageLoe): null; } }
- 미해결실전! Querydsl
안녕하세요. DTO 생성자에 매개변수를 엔티티로 설정하면 문제가 될 수 있나요?
안녕하세요.프로젝션으로 결과를 반환할 때 엔티티를 매개 변수로 받으면 안되는 건지 궁금증이 생겼습니다.@Data @NoArgsConstructor public class MemberDto { private String username; private int age; @QueryProjection public MemberDto(Member member) { this.username = member.getUsername(); this.age = member.getAge(); } }넣어주고자 하는 값이 많을 때 엔티티 자체를 넘겨주면 되지 않나? 라는 생각이 들어 케이스를 구글링해봤는데 모든 예제를 봤을 때 각각의 필요한 값만 매개변수로 설정하는 것으로 보이더라구요.혹시 그 이유가 있는것인지, 이렇게 매개변수를 엔티티로 받게 되면 문제가 될 부분이 있어서 사용을 하지 않는 것인지 궁금합니다.감사합니다!
- 미해결실전! Querydsl
querydsl로깅
[질문 내용]현재 제가 생성한 프로젝트에 builde.gradle파일이구요.jpa를 사용한 쿼리들은 로그에 파라미터가 잘찍히는데요.querydsl을 사용해서 나온 쿼리들은 로그에서 파라미터가 안보여서요. 혹시 해결방법 있을가요?plugins { id 'java' id 'org.springframework.boot' version '3.1.0' id 'io.spring.dependency-management' version '1.1.0' } group = 'study' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0' implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta' annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jakarta" annotationProcessor "jakarta.annotation:jakarta.annotation-api" annotationProcessor "jakarta.persistence:jakarta.persistence-api" } tasks.named('test') { useJUnitPlatform() }
- 해결됨실전! Querydsl
.join 사용 시 첫 번 째 파라미터 질문입니다.
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오) 예2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 예3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) 예[질문 내용]여기에 질문 내용을 남겨주세요.해당 두 코드 모두 같은 쿼리를 발생하고 있고 member.team또한 team 클래스를 바라보고 있습니다.둘이 동일한 코드라고 생각이 되었고 제 손은 계속해서 2번 째 코드를 작성하고 있는데 강사님께서 member.team으로 작성하신 이유가 있을거라는 생각이 되어 질문드립니다!혹시 강사님께서 member.team으로 작성하신 이유가 따로 있을까요??
- 미해결실전! Querydsl
EntityManager 관련 오류
em에 빨간줄이 들어와 클릭해보니 주입이 안된다고하는데 무엇이 문제일까요?Could not autowire. No beans of 'EntityManager' type found.
- 해결됨실전! Querydsl
update쿼리로 인한 영속성컨텍스트 불일치
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)[질문 내용]수정, 삭제 벌크 연산의 6:20 부분에서 update쿼리로 인한 영속성컨텍스트 문제를 설명해주셨는데요.전 강의에서 em.flush()실행되는 조건들을 설명해주실 때, 직접 호출 시트랜잭션 커밋 시 JPQL쿼리 실행 시 em.flush()가 실행된다고 설명해주신 것으로 기억하고 있습니다.querydsl도 결국 JPQL기반으로 작동된다고 알고 있는데, querydsl을 통한 select쿼리 실행을 하면 자동으로 em.flush()가 실행되지 않고, 직접 해주어야 하는 메커니즘이 궁금합니다!
- 미해결실전! Querydsl
@QueryProjection 관련 오류
강의 대로 Dto 생성자에 @QueryProjection 어노테이션 적용 후 컴파일하여 QMemberDto 클래스 생성 확인이 됐는데 , 테스트 시 위의 그림과 같이 빨간색처리 되며 없다고 뜬다. 무엇이 문제일까요?
- 해결됨실전! Querydsl
계층구조로 join이 일어나는 경우에 대한 질문입니다..
@Table(name = "a") @Entity @Getter public class AEntity { @Id @Column(name = "a_id") private Long aId; @OneToMany(mappedBy = "aEntity") List<BEntity> bList; public void initializeClist() { bList.stream().map(BEntity::getCList).forEach(Hibernate::initialize); } }@Table(name = "b") @Entity @Getter public class BEntity { @Id @Column(name = "b_id") private Long bId; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "a_id") private AEntity aEntity; @OneToMany(mappedBy = "bEntity") List<CEntity> cList; }@Table(name = "c") @Entity @Getter public class CEntity { @Id @Column(name = "c_id") private Long cId; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "b_id") private BEntity bEntity; }안녕하세요. 수업을 아직 수강중인 학생입니다.위와같이 A -> B -> C 아래로 OneToMany 관계로 LeftJoin을 해야한다고 하면어떤식으로 코드를 짜야하는 걸까요?displayRwdbJpaQueryFactory .selectFrom(QAEntity.aEntity) .leftJoin(QAEntity.aEntity.bList, QBEntity.bEntity) .fetchJoin().fetch();.fetchJoin을 써봤는데.. 한번은 되는데 두번은 안되더라구요..bList.stream().map(BEntity::getCList).forEach(Hibernate::initialize);@BatchSize 주고 위처럼 initialize 해봤는데..테이블 계층구조가 여기서 끝나는게 아니라서.. 이런식으로 처리 되기에는 조금 무리가 있을것 같습니다.장고끝에 조언을 구합니다.. 도와주세요.. ㅠㅠ
- 미해결실전! Querydsl
QueryDsl 의 Qclass 에 대해
Q클래스와 같이 엔티티가 하나씩 더 생기는 데 왜일까요? 괜찮은건가요?? 예 : Hello QHello 이렇게 사진 처럼 생기네요 .
- 미해결실전! Querydsl
내가 쓴 SpringBoot 2.7 에서의 queryDsl 설정 방법.
다른 블로그 참고하여 강의에 맞게 설정을 조금 수정하였습니다.새롭게 강의 듣는 분들의 시간을 아낄 수 있을까 싶어 공유드립니다.장점QEntity 생성 경로가 강의와 같습니다.src/main 하위가 아닌 generated 하위에만 QEntity 가 생성 되어 git ignore설정을 따로 해주지 않아도 됩니다.저도 이 강의의 이 회차를 듣고 알아본 것이기 때문에 QEntity 가 잘 생성되어 Run이 잘되는 것만 확인했지 다른 것까지 모두 테스트 해보진 못했습니다. compileQueryDsl 동작 없이 Application Run 하시면 되겠습니다.아래 설정의 잘못된점이 있다면 댓글 달아주시면 모두에게 도움이 될 것 같습니다.내 블로그 : https://elastinn.tistory.com/11블로그 광고해도 되나 모르겠습니다.감사합니다.plugins { id 'java' id 'org.springframework.boot' version '2.7.12' id 'io.spring.dependency-management' version '1.0.15.RELEASE' } group = 'study' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' // queryDSL 설정 implementation "com.querydsl:querydsl-jpa" implementation "com.querydsl:querydsl-core" implementation "com.querydsl:querydsl-collections" annotationProcessor "com.querydsl:querydsl-apt:${dependencyManagement.importedProperties['querydsl.version']}:jpa" // querydsl JPAAnnotationProcessor 사용 지정 annotationProcessor "jakarta.annotation:jakarta.annotation-api" // java.lang.NoClassDefFoundError (javax.annotation.Generated) 대응 코드 annotationProcessor "jakarta.persistence:jakarta.persistence-api" // java.lang.NoClassDefFoundError (javax.annotation.Entity) 대응 코드 runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' } tasks.named('test') { useJUnitPlatform() } //querydsl 추가 시작 def querydslDir = "$buildDir/generated/querydsl" // java source set 에 querydsl QClass 위치 추가 sourceSets { main.java.srcDirs += [ querydslDir ] } // gradle clean 시에 QClass 디렉토리 삭제 clean { delete file(querydslDir) } //querydsl 추가 끝
- 미해결실전! Querydsl
양방향 연관관계 편의메서드 작성시
QueryDSL 강의 예제 모델에서 , @Entity @Getter @Setter @NoArgsConstructor(access = AccessLevel.PROTECTED) @ToString(of = {"id", "username", "age"}) public class Member { @Id @GeneratedValue @Column(name = "member_id") private Long id; private String username; private int age; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "team_id") private Team team; public Member(String username, int age, Team team) { this.username = username; this.age = age; if (team != null) { changeTeam(team); } public void changeTeam(Team team) { this.team = team; team.getMembers().add(this); 이 부분에서 public void changeTeam(Team team) { this.team.getMembers().remove(this); this.team = team; team.getMembers().add(this);아래와 같이 해당 팀의 멤버 삭제도 해줘야 하는것 아닌가요? public void changeTeam(Team team){ if(this.team != null) { // this.team이 null이 아니면 이 member객체는 team이 있음을 의미 this.team.getMembers().remove(this); // 해당 팀의 멤버에서 삭제 } this.team = team; team.getMembers().add(this); }