inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발

주문 기능 테스트

테스트 exception 관련 질문 입니다.

1349

민경재

작성한 질문수 18

2

안녕하십니까 선생님의 강의 정말 유익하게 잘 보고 있습니다.

다름이아니라 상품주문 test 를 하게되면 
==== 오류

org.springframework.dao.InvalidDataAccessApiUsageException: id to load is required for loading; nested exception is java.lang.IllegalArgumentException: id to load is required for loading

이런식으로 납니다.그래서 id가 자동으로 생성이 안되는내용이라서 @GenereatedValue 가 이미 Item 에 id 에 선언되어있고 혹시나 해서 setId로 id 값 지정후 해보니 그다음으로는

== 오류 전문

java.lang.NullPointerException

at jpabook.jpashoop.service.OrderService.order(OrderService.java:41)

at jpabook.jpashoop.service.OrderService$$FastClassBySpringCGLIB$$f6e85b24.invoke(<generated>)

at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)

at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)

at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)

at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)

at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)

at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)

at jpabook.jpashoop.service.OrderService$$EnhancerBySpringCGLIB$$ac50f3a2.order(<generated>)

at jpabook.jpashoop.service.OrderServiceTest.상품주문(OrderServiceTest.java:44)

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:686)

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$6(TestMethodTestDescriptor.java:212)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)

at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)

at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)

at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)

at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)

at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)

at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)

at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)

at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)

at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)

at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)

at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)

at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)

at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)

at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)

at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)

at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)

at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)

at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)

at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)

at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)

at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)

at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)

at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

이런식으로 NullPointEception 이 일어납니다.
혹시 이렇게 되면 item class가 문제인지 또는 service 와 repository 문제인지 혹시 알고싶습니다.

JPA spring java spring-boot 웹앱

답변 4

11

김영한

안녕하세요^^ 코드를 확인해보았습니다.

[받은 코드]

    @Test
public void 상품주문() throws Exception{
//given
Member member = new Member();
member.setName("cs1");
member.setAddress(new Address("seoul","kkk","123-123"));
em.persist(member);

Item book = new Book();
// book.setId(1L);
book.setName("OldTown PJA");
book.setPrice(10000);
book.setStockQuantity(10);

int orderCount = 2;
//when
Long orderId = orderService.order(member.getId(), book.getId(), orderCount);

보내주신 코드에서 book.getId()를 호출하는 부분이 있습니다. 그런데 id가 없기 때문에 발생하는 문제입니다.

id가 다음과 같이 @GeneratedValue로 되어 있기 때문에 id를 생성하려면 엔티티를 DB에 저장해야 합니다.

@Id
@GeneratedValue
@Column(name = "item_id")
private Long id;

쉽게 이야기해서 em.persist(book)을 한번 호출해주시면 id가 생성되고, 엔티티 내부에 가져있게 됩니다.

그래서 다음과 같이 book 생성 마지막에 em.persist(book)을 추가해주시면 됩니다. 그러면 이후에는 book의 id필드에 pk값이 존재하게 됩니다.

        Item book = new Book();
// book.setId(1L);
book.setName("OldTown PJA");
book.setPrice(10000);
book.setStockQuantity(10);
em.persist(book);

아마도 id 생성과 식별자가 어떻게 만들어지는지 등등 많이 궁금하실꺼에요. 이 부분은 JPA 기본편에서 자세히 알려드립니다^^!

도움이 되셨길 바래요.

1

김영한

네 끝까지 화이팅입니다^^!

1

민경재

감사합니다. JPA1 다보고 기본보고 다시 JPA1 하려고하는데 이런문제가 발생한거 같습니다 ㅠㅠ 다시한번 감사 드립니다.

1

김영한

안녕하세요. 민경재님^^

전체 프로젝트를 압축해서 올려주세요.

sdk 설정 오류

0

53

2

오탈자 - @Transactional

0

56

1

src/test/resources 테스트 경로 문제

0

50

1

상품 등록후 H2 db 출력 순서 바꿀 수 있나요?

0

64

1

MemberRepositoryTest 실행오류

0

81

1

boot 4.x >>> trasasction rolled back log & p6spy(영한님, 수업 자료 업데이트 해주시면 감사하겠습니다!!)

1

183

2

강의 마지막 QueryDSL 사용 부분 질문있습니다

1

142

2

클라이언트에서 isbn과 author 수정 요청을 한 경우에 대해 질문드립니다.

0

51

1

도메인 모델 패턴 vs 트랜잭션 스크립트 패턴

0

71

1

기본 생성자

0

60

1

h2 DB 연결시 jdbc url 변경 이유가 궁금합니다.

0

102

1

멤버서비스테스트 부분에서 막힙니다.

0

165

4

실무에서도 EntityManager를 이용해서 많이 작업하는 편일까요?

0

116

1

초반에 h2 다운로드 과정 꼭 필요한가요?

0

120

2

자신 필드에도 get으로 접근하는 이유가 있을까요?

0

114

1

24분 27초 연관관계 편의 메서드 위치

0

113

1

단건 주문만 가능하게 한건 의도한 부분이신가요?

0

109

2

빌드 툴, Gradle

0

59

1

h2연결은 된 것 같은데 엔티티 테이블까지 작성 후 확인해보아도 테이블이 안보입니다

0

77

2

Repository에서 EntityManager 주입 방식 차이

0

90

1

롬복과 사용자 정의 setter 메서드

0

72

1

주문 목록 조회 fetch join 질문드립니다

0

82

1

dirty checking 질문드립니다.

0

83

1

동시성 관련 질문입니다

0

75

1