인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

literate_t님의 프로필 이미지
literate_t

작성한 질문수

스프링 DB 2편 - 데이터 접근 활용 기술

스프링 데이터 JPA 적용2

Item find 관련한 쿼리 메소드 작성에 대한 질문 겸 참고사항입니다!

작성

·

417

0

=========================================
[질문 템플릿]
1. 강의 내용과 관련된 질문인가요? (예)
2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)
3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)

[질문 내용]
>> 로컬 환경
윈도우 10
hibernate-core:6.2.5.Final
spring boot:3.0.1

아이템 조회하는 부분에서 강의와 똑같이 오류가 발생했었는데요. 지금 버전에서는 findByItemName 혹은 findByItemNameContaining 모두 정상 작동합니다.
다른 부분에서 오류가 발생해서 찾아보니까 findItems에 작성된 JPQL에서 like 뒤에 변수 기입할 때 %를 넣지 않아서 그런 거더라고요. 넣으니 테스트 통과합니다 :-)

    @Query("select i from Item i where i.itemName like %:itemName% and i.price <= :price")
    List<Item> findItems(@Param("itemName") String itemName, @Param("price") Integer price);

저만 겪은 오류인가 싶기도 한데 혹시 몰라서 공유해봅니다. 감사합니다.

ps. 제가 겪은 에러는 문법 오류라고 알려주지 않는 것 같네요. 어렵습니다ㅠ

12:17:43.066 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [hello.itemservice.domain.ItemRepositoryTest]: ItemRepositoryTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
12:17:43.135 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration hello.itemservice.ItemServiceApplication for test class hello.itemservice.domain.ItemRepositoryTest

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.1.1)

2023-07-04T12:17:43.419+09:00  INFO 26524 --- [           main] h.itemservice.domain.ItemRepositoryTest  : Starting ItemRepositoryTest using Java 17.0.7 with PID 26524 (started by taetae in D:\source codes\intellij\itemservice-db)
2023-07-04T12:17:43.420+09:00  INFO 26524 --- [           main] h.itemservice.domain.ItemRepositoryTest  : The following 1 profile is active: "test"
2023-07-04T12:17:43.813+09:00  INFO 26524 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-07-04T12:17:43.858+09:00  INFO 26524 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 37 ms. Found 1 JPA repository interfaces.
2023-07-04T12:17:44.197+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.DataSourceUtils      : Fetching JDBC Connection from DataSource
2023-07-04T12:17:44.197+09:00  INFO 26524 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-07-04T12:17:44.323+09:00  INFO 26524 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:be66698a-0e22-4c39-868d-4400050c76bd user=SA
2023-07-04T12:17:44.324+09:00  INFO 26524 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-07-04T12:17:44.336+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.DataSourceUtils      : Fetching JDBC Connection from DataSource
2023-07-04T12:17:44.337+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from file [D:\source codes\intellij\itemservice-db\out\test\resources\schema.sql]
2023-07-04T12:17:44.340+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : 0 returned as update count for SQL: drop table if exists item CASCADE
2023-07-04T12:17:44.346+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : 0 returned as update count for SQL: create table item ( id bigint generated by default as identity, item_name varchar(10), price integer, quantity integer, primary key (id) )
2023-07-04T12:17:44.347+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from file [D:\source codes\intellij\itemservice-db\out\test\resources\schema.sql] in 9 ms.
2023-07-04T12:17:44.374+09:00 DEBUG 26524 --- [           main] o.s.jdbc.datasource.DataSourceUtils      : Fetching JDBC Connection from DataSource
2023-07-04T12:17:44.396+09:00  INFO 26524 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2023-07-04T12:17:44.437+09:00  INFO 26524 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 6.2.5.Final
2023-07-04T12:17:44.440+09:00  INFO 26524 --- [           main] org.hibernate.cfg.Environment            : HHH000406: Using bytecode reflection optimizer
2023-07-04T12:17:44.534+09:00  INFO 26524 --- [           main] o.h.b.i.BytecodeProviderInitiator        : HHH000021: Bytecode provider name : bytebuddy
2023-07-04T12:17:44.638+09:00  INFO 26524 --- [           main] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer
2023-07-04T12:17:44.813+09:00  INFO 26524 --- [           main] o.h.b.i.BytecodeProviderInitiator        : HHH000021: Bytecode provider name : bytebuddy
2023-07-04T12:17:45.187+09:00  INFO 26524 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2023-07-04T12:17:45.197+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : drop table if exists item cascade 
2023-07-04T12:17:45.200+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : create table item (price integer, quantity integer, id bigint generated by default as identity, item_name varchar(10), primary key (id))
2023-07-04T12:17:45.203+09:00  INFO 26524 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2023-07-04T12:17:45.369+09:00  WARN 26524 --- [           main] ocalVariableTableParameterNameDiscoverer : Using deprecated '-debug' fallback for parameter name resolution. Compile the affected code with '-parameters' instead or avoid its introspection: hello.itemservice.repository.jpa.SpringDataJpaItemRepository
2023-07-04T12:17:45.426+09:00  INFO 26524 --- [           main] o.s.d.j.r.query.QueryEnhancerFactory     : Hibernate is in classpath; If applicable, HQL parser will be used.
2023-07-04T12:17:45.747+09:00  WARN 26524 --- [           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 warning
2023-07-04T12:17:45.875+09:00  INFO 26524 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
2023-07-04T12:17:46.137+09:00  INFO 26524 --- [           main] h.itemservice.domain.ItemRepositoryTest  : Started ItemRepositoryTest in 2.883 seconds (process running for 3.558)
OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
2023-07-04T12:17:46.518+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : insert into item (item_name,price,quantity,id) values (?,?,?,default)
2023-07-04T12:17:46.543+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : insert into item (item_name,price,quantity,id) values (?,?,?,default)
2023-07-04T12:17:46.544+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : insert into item (item_name,price,quantity,id) values (?,?,?,default)
2023-07-04T12:17:46.594+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0
2023-07-04T12:17:46.633+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0
2023-07-04T12:17:46.645+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0 where i1_0.item_name like ? escape '\'
2023-07-04T12:17:46.648+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0 where i1_0.item_name like ? escape '\'
2023-07-04T12:17:46.649+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0 where i1_0.item_name like ? escape '\'
2023-07-04T12:17:46.651+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0 where i1_0.price<=?
2023-07-04T12:17:46.656+09:00 DEBUG 26524 --- [           main] org.hibernate.SQL                        : select i1_0.id,i1_0.item_name,i1_0.price,i1_0.quantity from item i1_0 where i1_0.item_name like ? escape '' and i1_0.price<=?

org.opentest4j.AssertionFailedError: 
Expecting actual:
  []
to contain exactly (and in same order):
  [Item(id=1, itemName=itemA-1, price=10000, quantity=10)]
but could not find the following elements:
  [Item(id=1, itemName=itemA-1, price=10000, quantity=10)]

Expected :[Item(id=1, itemName=itemA-1, price=10000, quantity=10)]
Actual   :[]
<Click to see difference>


	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
	at hello.itemservice.domain.ItemRepositoryTest.test(ItemRepositoryTest.java:107)
	at hello.itemservice.domain.ItemRepositoryTest.findItems(ItemRepositoryTest.java:102)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
	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:156)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
	at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
	at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
	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.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
	at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
	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:1511)
	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:1511)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java: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:232)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)

2023-07-04T12:17:46.678+09:00  INFO 26524 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2023-07-04T12:17:46.678+09:00 DEBUG 26524 --- [ionShutdownHook] org.hibernate.SQL                        : drop table if exists item cascade 
2023-07-04T12:17:46.680+09:00  INFO 26524 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2023-07-04T12:17:46.681+09:00  INFO 26524 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code -1

답변 1

1

안녕하세요. literate_t님, 공식 서포터즈 David입니다.

공유 감사합니다.

질문자 분께서 마주한 것은 에러는 아니고, 테스트 실패로 보여집니다.

특정 Item이 올 것을 기대했으나 실제로는 아무것도 존재하지 않아서 테스트가 실패한 것 같습니다.

비교 대상이 되는 실제 값이 존재하는지부터 디버깅 해보시면 좋을 것 같습니다.

감사합니다.


literate_t님의 프로필 이미지
literate_t
질문자

아이템 조회가 되지 않아 테스트가 통과 못한 이유는 쿼리 문제였습니다.
like %:itemName%으로 해줘야 하는데 강의나, 교안에서 모두 누락되어 있었습니다.

literate_t님의 프로필 이미지
literate_t

작성한 질문수

질문하기