묻고 답해요
160만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
orderItem이 casecade가 안걸려있다고 생각하고 질문 드립니다.
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)예2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 예3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)예[질문 내용]casecade로 persist를 한번에 진행하는데이제 각자 등록해야 된다면(cascade이 애매하게 느껴진다면)public void save(Order order){ em.persist(order.getOrderItem()) em.persist(order.getDelivery()) em.persist(order.getMember()) em.persist(order);이런식으로 persist를 진행하면 되는걸까요?
-
해결됨자바 ORM 표준 JPA 프로그래밍 - 기본편
상속관계가 두 개 이상일 때 매핑 질문
안녕하세요.하나의 엔티티가 두 개 이상의 상위 엔티티에 속하는 경우 어떻게 구현해야 하는지 질문드립니다.예를 들어서 사과라는 엔티티가 과일에도 속하고 음식에도 속한다고 했을 때,DB에서는 사과엔티티를 과일테이블과 음식테이블이라는 두 개의 싱글테이블의 행으로 표현할 수 있지만 객체모델링에서는 사과가 반드시 하나의 엔티티 클래스를 상속해야하기 때문에 어떻게 모델링해야 하는지 모르겠습니다.감사합니다.
-
미해결Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)
특정 도구에서 서버를 실행하면 에러가 발생합니다.
안녕하세요. 강의를 들으면서 코드를 실행하다가 막힌 부분이 있어 질문드립니다.특정 도구에서 사용하면 서버가 실행이 되지 않습니다.인텔리제이 터미널에서 실행한 경우 에러가 발생합니다.PS C:\workplace\user-service> mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=9003' -e[INFO] Error stacktraces are turned on.[INFO] Scanning for projects...[INFO] [INFO] ----------------------< com.example:user-service >----------------------[INFO] Building user-service 0.0.1-SNAPSHOT[INFO] from pom.xml[INFO] --------------------------------[ jar ]---------------------------------[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 0.326 s[INFO] Finished at: 2023-06-27T21:49:08+09:00[INFO] ------------------------------------------------------------------------[ERROR] Unknown lifecycle phase ".run.jvmArguments=-Dserver.port=9003". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: pre-clean, clean, post-clean, validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-site, site, post-site, site-deploy. -> [Help 1]org.apache.maven.lifecycle.LifecyclePhaseNotFoundException: Unknown lifecycle phase ".run.jvmArguments=-Dserver.port=9003". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: pre-clean, clean, post-clean, validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-site, site, post-site, site-deploy. at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateLifecycleMappings (DefaultLifecycleExecutionPlanCalculator.java:225) at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateMojoExecutions (DefaultLifecycleExecutionPlanCalculator.java:197) at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan (DefaultLifecycleExecutionPlanCalculator.java:119) at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan (DefaultLifecycleExecutionPlanCalculator.java:135) at org.apache.maven.lifecycle.internal.builder.BuilderCommon.resolveBuildPlan (BuilderCommon.java:93) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:100) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:261) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:173) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:101) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:906) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:283) at org.apache.maven.cli.MavenCli.main (MavenCli.java:206) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:566) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:283) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:226) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:407) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:348)[ERROR][ERROR] Re-run Maven using the -X switch to enable full debug logging.[ERROR][ERROR] For more information about the errors and possible solutions, please read the following articles:[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException PowerShell에서 실행한 경우 에러가 발생합니다.PS C:\workplace\user-service> java -jar -Dserver.port=9004 .\target\user-service-0.0.1-SNAPSHOT.jarError: Unable to access jarfile .port=9004※ PowerShell에서 실행한 명령어를 명령 프롬프트에서 실행하면 정상작동됩니다.감사합니다.
-
해결됨자바 ORM 표준 JPA 프로그래밍 - 기본편
DTYPE을 코드로 표현하는 경우
안녕하세요.DiscriminatorColumn, DiscriminatorValue 를 이용하여 DTYPE을 자동으로 insert하는 기능이 참 편리해보이는데요.만약에 예시에 나온 Item의 관리가 객체 이름이 아닌 일련의 문자열 ItemCode로 이루어진다면, 그리고 ItemCode를 DB 등에 따로 저장하여 사용하고 있다면 DiscriminatorValue에 그 값을 넣어줄 수 있는 방법이 있을까요?만약 DB에서 조회하는 것이 불가능하다면 DB가 아니라 코드로 정의를 해놓는다면(Enum등으로) 참조값을 넣어줄 수는 있을까요?감사합니다.
-
해결됨스프링과 JPA 기반 웹 애플리케이션 개발
사진 수정이 계속 안 됩니다.
cdn 방식으로 cropper를 사용하는 중이고요. 자바스크립트를 여러번 검토 하였음에도 프로필 사진 변경 문제는 끝까지 해결되지 않았습니다.https://www.youtube.com/watch?v=k330LVo2yw8setting.profile.html<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://thymeleaf.org/extras/spring-security"> <head th:fragment="head"> <meta charset="UTF-8"> <title>StudyOlle</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/jdenticon@3.2.0/dist/jdenticon.min.js" async integrity="sha384-yBhgDqxM50qJV5JPdayci8wCfooqvhFYbIKhv0hTtLvfeeyJMJCscRfFNKIxt43M" crossorigin="anonymous"> </script> <style> .container{ max-width:100%; } </style> </head> <nav th:fragment="main-nav" class="navbar navbar-expand-sm navbar-dark bg-dark"> <a class="navbar-brand" href="/" th:href="@{/}"> <img src="/images/logo_sm.png" width="30" height="30"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <form th:action="@{/search/study}" class="form-inline" method="get"> <input class="form-control mr-sm-2" name="keyword" type="search" placeholder="스터디 찾기" aria-label="Search"> </form> </li> </ul> <ul class="navbar-nav justify-content-end"> <li class="nav-item" sec:authorize="isAnonymous()"> <a class="nav-link" th:href="@{/login}">로그인</a> </li> <li class="nav-item" sec:authorize="isAnonymous()"> <a class="nav-link" th:href="@{/sign-up}">가입</a> </li> <li class="nav-item" sec:authorize="isAuthenticated()"> <a class="nav-link" th:href="@{/notifications}"> <i class="fa fa-bell-o" aria-hidden="true"></i> </a> </li> <li class="nav-item" sec:authorize="isAuthenticated()"> <a class="nav-link btn btn-outline-primary" th:href="@{/notifications}"> <i class="fa fa-plus" aria-hidden="true"></i> 모임 개설 </a> </li> <li class="nav-item dropdown" sec:authorize="isAuthenticated()"> <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <svg th:if="${#strings.isEmpty(account?.profileImage)}" th:data-jdenticon-value="${#authentication.name}" width="24" height="24" class="rounded border bg-light"></svg> <img th:if="${!#strings.isEmpty(account?.profileImage)}" th:src="${account.profileImage}" width="24" height="24" class="rounded border"/> </a> <div class="dropdown-menu dropdown-menu-sm-right" aria-labelledby="userDropdown"> <h6 class="dropdown-header"> <span sec:authentication="name">Username</span> </h6> <a class="dropdown-item" th:href="@{'/profile/' + ${#authentication.name}}">프로필</a> <a class="dropdown-item" >스터디</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#" th:href="@{'/settings/profile'}">설정</a> <form class="form-inline my-2 my-lg-0" action="#" th:action="@{/logout}" method="post"> <button class="dropdown-item" type="submit">로그아웃</button> </form> </div> </li> </ul> </div> </nav> <footer th:fragment="footer"> <div class="row justify-content-center"> <img class="mb-2" src="/images/logo_lang_kr.jpg" alt="" width="100"> <small class="d-block mb-3 text-muted">© 2023</small> </div> </footer> <div th:fragment="settings-menu (currentMenu)" class="list-group"> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'profile'}? active" href="#" th:href="@{/settings/profile}">프로필</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'password'}? active" href="#" th:href="@{/settings/password}">비밀번호</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'notification'}? active" href="#" th:href="@{/settings/notification}">알림</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'tags'}? active" href="#" th:href="@{/settings/tags}">관심 주제</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'zones'}? active" href="#" th:href="@{/settings/zones}">활동 지역</a> <a class="list-group-item list-group-item-action list-group-item-danger" th:classappend="${currentMenu == 'account'}? active" href="#" th:href="@{/settings/account}">계정</a> </div> <script type="application/javascript" th:fragment="form-validation"> (function () { 'use strict'; window.addEventListener('load', function () { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission Array.prototype.filter.call(forms, function (form) { form.addEventListener('submit', function (event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated') }, false) }) }, false) }()) </script> </html>fragments.html<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://thymeleaf.org/extras/spring-security"> <head th:fragment="head"> <meta charset="UTF-8"> <title>StudyOlle</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/jdenticon@3.2.0/dist/jdenticon.min.js" async integrity="sha384-yBhgDqxM50qJV5JPdayci8wCfooqvhFYbIKhv0hTtLvfeeyJMJCscRfFNKIxt43M" crossorigin="anonymous"> </script> <style> .container{ max-width:100%; } </style> </head> <nav th:fragment="main-nav" class="navbar navbar-expand-sm navbar-dark bg-dark"> <a class="navbar-brand" href="/" th:href="@{/}"> <img src="/images/logo_sm.png" width="30" height="30"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <form th:action="@{/search/study}" class="form-inline" method="get"> <input class="form-control mr-sm-2" name="keyword" type="search" placeholder="스터디 찾기" aria-label="Search"> </form> </li> </ul> <ul class="navbar-nav justify-content-end"> <li class="nav-item" sec:authorize="isAnonymous()"> <a class="nav-link" th:href="@{/login}">로그인</a> </li> <li class="nav-item" sec:authorize="isAnonymous()"> <a class="nav-link" th:href="@{/sign-up}">가입</a> </li> <li class="nav-item" sec:authorize="isAuthenticated()"> <a class="nav-link" th:href="@{/notifications}"> <i class="fa fa-bell-o" aria-hidden="true"></i> </a> </li> <li class="nav-item" sec:authorize="isAuthenticated()"> <a class="nav-link btn btn-outline-primary" th:href="@{/notifications}"> <i class="fa fa-plus" aria-hidden="true"></i> 모임 개설 </a> </li> <li class="nav-item dropdown" sec:authorize="isAuthenticated()"> <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <svg th:if="${#strings.isEmpty(account?.profileImage)}" th:data-jdenticon-value="${#authentication.name}" width="24" height="24" class="rounded border bg-light"></svg> <img th:if="${!#strings.isEmpty(account?.profileImage)}" th:src="${account.profileImage}" width="24" height="24" class="rounded border"/> </a> <div class="dropdown-menu dropdown-menu-sm-right" aria-labelledby="userDropdown"> <h6 class="dropdown-header"> <span sec:authentication="name">Username</span> </h6> <a class="dropdown-item" th:href="@{'/profile/' + ${#authentication.name}}">프로필</a> <a class="dropdown-item" >스터디</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#" th:href="@{'/settings/profile'}">설정</a> <form class="form-inline my-2 my-lg-0" action="#" th:action="@{/logout}" method="post"> <button class="dropdown-item" type="submit">로그아웃</button> </form> </div> </li> </ul> </div> </nav> <footer th:fragment="footer"> <div class="row justify-content-center"> <img class="mb-2" src="/images/logo_lang_kr.jpg" alt="" width="100"> <small class="d-block mb-3 text-muted">© 2023</small> </div> </footer> <div th:fragment="settings-menu (currentMenu)" class="list-group"> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'profile'}? active" href="#" th:href="@{/settings/profile}">프로필</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'password'}? active" href="#" th:href="@{/settings/password}">비밀번호</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'notification'}? active" href="#" th:href="@{/settings/notification}">알림</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'tags'}? active" href="#" th:href="@{/settings/tags}">관심 주제</a> <a class="list-group-item list-group-item-action" th:classappend="${currentMenu == 'zones'}? active" href="#" th:href="@{/settings/zones}">활동 지역</a> <a class="list-group-item list-group-item-action list-group-item-danger" th:classappend="${currentMenu == 'account'}? active" href="#" th:href="@{/settings/account}">계정</a> </div> <script type="application/javascript" th:fragment="form-validation"> (function () { 'use strict'; window.addEventListener('load', function () { // Fetch all the forms we want to apply custom Bootstrap validation styles to var forms = document.getElementsByClassName('needs-validation'); // Loop over them and prevent submission Array.prototype.filter.call(forms, function (form) { form.addEventListener('submit', function (event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated') }, false) }) }, false) }()) </script> </html>SettingsController.java@Controller @RequiredArgsConstructor public class SettingsController { final static String SETTING_PROFILE_VIEW_NAME="settings/profile"; final static String SETTING_PROFILE_URL="/settings/profile"; private final AccountService accountService; @GetMapping(SETTING_PROFILE_URL) public String profileUpdateForm(@CurrentUser Account account, Model model){ model.addAttribute(account); model.addAttribute(new Profile(account)); return SETTING_PROFILE_VIEW_NAME; } @PostMapping(SETTING_PROFILE_URL) public String updateProfile(@CurrentUser Account account, @Valid Profile profile, Errors errors, Model model, RedirectAttributes attributes){ if(errors.hasErrors()){ model.addAttribute(account); return SETTING_PROFILE_VIEW_NAME; } accountService.updateProfile(account, profile); attributes.addFlashAttribute("message","프로필을 수정했습니다."); return "redirect:"+SETTING_PROFILE_URL; } }AccountService.javapublic void updateProfile(Account account, Profile profile){ account.setUrl(profile.getUrl()); account.setBio(profile.getBio()); account.setOccupation(profile.getOccupation()); account.setLocation(profile.getLocation()); account.setProfileImage(profile.getProfileImage()); accountRepository.save(account); }Profile.java@Data @NoArgsConstructor public class Profile { @Length(max = 35) private String bio; @Length(max = 50) private String url; @Length(max = 50) private String occupation; @Length(max = 50) private String location; private String profileImage; public Profile(Account account){ this.bio=account.getBio(); this.url=account.getUrl(); this.occupation=account.getOccupation(); this.location=account.getLocation(); this.profileImage=account.getProfileImage(); } }
-
미해결실전! 스프링 데이터 JPA
부모 엔티티의 Respository 로 저장시 자식 엔티티의 영속성 전이 문제
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)[질문 내용]김영한님 안녕하세요. JPA 사용중에 부모 엔티티의 Respository 로 저장시 자식 엔티티의 영속성 전이 문제가 있어 질문 남깁니다. 상황은 다음과 같습니다.게시판과 게시판의 댓글을 하나의 애그리거트로 보고 게시판(루트 애그리더트)을 통해 댓글을 작성하려고 합니다. 댓글의 게시판 칼럼을 세팅하고 게시판의 repository로 save 하게 되면 댓글이 영속성 상태가 되지 않습니다. 근데 게시판 내부에 있는 댓글 리스트에 추가된 신규 댓글을 영속성 상태입니다. (영속성 상태 여부는 id 값 존재 여부로 판단했습니다.) 위 캡쳐에서 board 의 commentList의 인덱스가 4인 BoardComment 를 보시면 id가 7로 세팅 되어 있지만, boardComment 의 id는 null 로 되어 있습니다. 그래서 물어보고 싶은건 다음과 같습니다.위 상황에서 boardComment 의 id 가 7(null 이 아닌)이 될 수 있는 방법댓글 조회/수정/삭제에서 DDD 를 적용했을때의 로직 DDD 에 맞게 루트 애그리거트를 통한 CRUD 를 만들려고 하다보니 이런 질문을 하게 되었습니다. 이 문제의 전체코드는 https://github.com/SongHae8640/community 이고, 위 테스트 코드는 https://github.com/SongHae8640/community/blob/master/src/test/java/com/example/community/domain/board/comment/BoardCommentTest.java 입니다. 확인 부탁드립니다.감사합니다.
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
변경감지 시 참조키 업데이트 질문드려요
변경감지를 통해서 데이터들을 업데이트하려고 하는데요.그 중에 외래키도 업데이트를 시키려고 하는데 변경감지로 잡히지가 않아서요.외래키는 변경감지에 안걸리나요?아래 예제입니다. class Team () {String teamName; @ManyToOne()@JoinColumn(name = "MEBER_SEQ")Member member;} Member newMember = new Member();team.setMember(newMember);
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
Test 작성 중 select 쿼리가 발생하지 않는다고 했는데, 저는 발생하고 있습니다.
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오) 네2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 네3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) 네[질문 내용]MemberRepositoryTest.java위 코드에서 테스트 진행했을 때, select 쿼리가 로그에 찍히고 있습니다. select 쿼리가 로그에 찍히는 이유를 알 수 있을까요? ( 강의 중 19:20 - 19:30 에 select 쿼리가 안 찍히는 게 정상이라고 하셔서 질문 드립니다. )아래는 application.yml 파일입니다. 아래는 select 쿼리가 찍힌 로그 입니다.감사합니다.
-
미해결실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
Order의 전체조회를 할때 조회타입 생략이 가능한가요?
실수로 생략하고 실행했는데 조회는 정상적으로 작동합니다.타입을 지정해야하는 상황과 지정하지 않아도 되는 상황을 예시로 명확히 설명해주실 수 있을까용?
-
미해결Practical Testing: 실용적인 테스트 가이드
DTO 분리에 관련된 질문이 있습니다.
안녕하세요. 강의 잘 듣고 있습니다.만약에 Service를 Write / Read 로 나눠서 관리를 한다고 하면Service 패키지쪽의 DTO도 나눠서 생성을 하시나요?아니면 그 부분은 같이 사용하시는 편인가요?
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
다대일 단방향으로 save시
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오) 예2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 예3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) 예[질문 내용]안녕하세요 질문 드리고 싶은건 팀과 멤버 엔티티를 DB에 저장하기 위한 상황입니다.한번의 save 코드로 두번의 INSERT 쿼리를 내보내겠습니다. 팀 save, 멤버 save (멤버 ManyToOne)팀.add멤버(멤버) 후 팀 save (팀 OneToMany, 멤버 ManyToOne)멤버.set팀(팀) 후 멤버 save (멤버 ManyToOne)이런 3가지 방법이 가능할 것 같습니다.3번의 경우에는 멤버에만 @ManyToOne으로 관계지정하고 cascade = CascadeType.ALL 옵션을 추가해서 팀에도 쿼리가 발생하게 되는데요이런 예시(Case. 3)가 웹에는 흔하지 않다는게 의문입니다.만약 cascade 옵션을 이렇게 사용해선 안되는 것인지. (자식엔티티로 부모 엔티티를 관여하는) 혹은 권장되는 방식인지.또 여러개의 테이블이 산재된 현업에서 어떤 방식이 권장되는지.이때 판단 기준은 어때야 하는지 궁금합니다.혹시 이런 내용을 책에서 다루고 있거나, 다른 강의에서 다루고 있다면 추천해주시면 구입해서 공부하고 싶습니다.항상 학생들을 위해 힘써주시고 좋은 강의 만들어주셔서 감사합니다.
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
could not instantiate id generator 에러가 발생합니다.
JpashopApplication 실행 시 다음과 같은 에러가 발생합니다.. Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not instantiate id generator [entity-name=jpabook.jpashop.domain.OrderItem] 본 파일에서는 삭제했는데 이전에 MemberRepositoryTest 실행 시에도 같은 에러가 발생해서 @GeneratedValue에 옵션설정을 추가했더니 @GeneratedValue(strategy = GenerationType.IDENTITY) 작동이 되더라구요. 이번에도 다 넣어줘야 하는건지 아니면 다른 이유 때문인지 궁금하여 글 남깁니다. 압축파일 링크 입니다. https://drive.google.com/file/d/1Uj__VLj3glPm6Uor6-Gyr6dX2i8kOQcc/view?usp=share_link 감사합니다 ^^
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
Junit4 -> Junit5로 테스트 적용 시
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]여기에 질문 내용을 남겨주세요.@Test(expected = IllegalStateException.class) public void 중복_회원_예외() throws Exception{ //given Member member1 = new Member(); member1.setName("kim"); Member member2 = new Member(); member2.setName("kim"); //when memberService.join(member1); memberService.join(member2); //then } }Junit5로 적용 시키고 싶어서 아래와 같이 테스트 코드를 작성했는데, 잘 작성한게 맞나요? 혹시 더 좋은 BestPractice가 있다면, 알려주시면 감사하겠습니다. @Test public void 중복_회원_예외() throws Exception{ //given Member member1 = new Member(); member1.setName("kim"); Member member2 = new Member(); member2.setName("kim"); //when memberService.join(member1); //then assertThrows(IllegalStateException.class, () -> {memberService.join(member2);}); } }
-
해결됨실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
서비스 단계에서 DTO를 사용하지 않고 엔티티를 바로 써도 되나요?
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]여기에 질문 내용을 남겨주세요. 강의를 수강 후 엔티티대신 DTO를 서비스에서 사용해야하는지 의문이 생겼습니다.controller 에서는 엔티티형태로 반환해서도 파라미터로 받아서도 안되는것을 이해했습니다.service 에서는 화면으로 보여지기 전에 controller 에서 DTO 형태로 가공할 수 있기 때문에 service 에서는 엔티티형태로 반환하고 파라미터로 받아도 되나요?1번이 아니라면 service 에서 DTO를 사용해야하는 경우나 안사용해도 되는 경우나 약간의 가이드를 주시면 감사하겠습니다.
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
메인 메서드 실행시 NoSuchMethodError 해결방법 공유
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)질문은 아니지만 해결방법이 안 올라온 것 같아 올립니다.2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)예3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)예[질문 내용]강의 초반에 Member 클래스를 만들고 DB연결, 테이블 생성까지 했는데 메인메서드를 실행하면 NoSuchMethodError 오류가 나는 경우가 있습니다.커뮤니티 게시판을 찾아봤는데 질문은 있고 답변은 없는 것 같아 해결방법 공유합니다.저같은 경우는 h2버전과 스프링 부트 버전이 맞지 않아 그런 줄 알고 h2와 스프링 부트 버전을 달리해가며 설정해봤는데 알고보니 hibernate 버전 충돌 문제인 것 같습니다.pom.xml파일에서<!-- JPA 하이버네이트 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.15.Final</version> </dependency>로 하이버네이트 의존성 설정을 해주면 인텔리제이가 자동으로 하이버네이트 라이브러리를 다운받는데 이때 hibernate-commons-annotations의 버전과 hibernate-core의 버전이 호환되지 않는 경우가 있는 것 같습니다. 저는 처음에 hibernate-commons-annotations 버전이 5.0.4, hibernate-core가 5.6.15 final로 되어있었는데 의존성 설정 갱신 이후 hibernate-commons-annotations 버전이 5.1.2 final로 바뀌며 정상 실행 됐습니다.인텔리제이가 충돌하는 라이브러리를 다운받기도 하는 것 같습니다.
-
미해결실전! 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
-
미해결더 자바, 코드를 조작하는 다양한 방법
Spring Data JPA 동적 프록시를 사용 질문
안녕하세요! 강의를 듣다가 궁금한 것이 생겨 질문 남깁니다 :) 찾아보니까 Spring 에서는 기본적으로 다이나믹 프록시를 사용하고, Spring Boot 에서는 기본적으로 CGLIB 사용으로 바뀌었다고 나와있습니다! Spring Boot 에서 Spring Data JPA 를 사용하여 Repository를 만들 때는 인터페이스 기반이기 때문에 디폴트 설정인 CGLIB 대신 다이나믹 프록시를 사용하는 것으로 이해했는데 맞을까요?!
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
p6spy 1.9.0 -> 1.8.1 버전 관련 내용 공유
p6spy releases를 확인해보면 1.9.0부터 Spring boot 3을 지원한다고 되어있고 테스트시 로그가 안뜹니다. 다른 질문에서보니 해당 버전이 메이븐에서만 지원되어서 그런 듯 합니다.그래서 바로 아래 버전인 1.8.1을 사용해서 정상적으로 로그가 뜨는 것을 확인했습니다.그래서 앞으로 최신 버전으로 했을때 안뜬다면 버전을 내려보시면 좋을 것 같습니다.
-
미해결실전! 스프링 데이터 JPA
JpaRepository 오버라이드 메소드에 QueryHints 적용시 에러발생
@QueryHints(value = @QueryHint(name = "org.hibernate.readOnly", value = "true")) @Override Optional<Member> findById(Long aLong);위와 같이 SimpleJpaRepository의 findById를 오버라이딩 할 경우 오류가 발생합니다.JpaRepository의 메소드를 오버라이드 하여서 적용할 수 없는건지 궁금합니다.다음은 오류의 내용입니다.org.springframework.dao.InvalidDataAccessApiUsageException: class java.lang.String cannot be cast to class java.lang.Boolean (java.lang.String and java.lang.Boolean are in module java.base of loader 'bootstrap'); nested exception is java.lang.IllegalArgumentException: class java.lang.String cannot be cast to class java.lang.Boolean (java.lang.String and java.lang.Boolean are in module java.base of loader 'bootstrap') at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:374) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:235) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:241) at com.sun.proxy.$Proxy132.findById(Unknown Source) at study.datajpa.MemberRepositoryTest.queryHint(MemberRepositoryTest.java:318) 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) Suppressed: org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:752) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) at org.springframework.test.context.transaction.TransactionContext.endTransaction(TransactionContext.java:131) at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:255) at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:445) at org.springframework.test.context.junit.jupiter.SpringExtension.afterEach(SpringExtension.java:206) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$12(TestMethodTestDescriptor.java:257) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:273) at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$14(TestMethodTestDescriptor.java:273) at java.base/java.util.ArrayList.forEach(ArrayList.java:1541) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:272) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:256) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:141) ... 47 moreCaused by: java.lang.IllegalArgumentException: class java.lang.String cannot be cast to class java.lang.Boolean (java.lang.String and java.lang.Boolean are in module java.base of loader 'bootstrap') at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3434) at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3380) 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.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:315) at com.sun.proxy.$Proxy112.find(Unknown Source) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById(SimpleJpaRepository.java:335) 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.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530) at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286) at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164) at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:76) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ... 77 moreCaused by: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Boolean (java.lang.String and java.lang.Boolean are in module java.base of loader 'bootstrap') at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3396) ... 106 more
-
미해결실전! 스프링 데이터 JPA
fetch하지 않은 left join은 member만 조회하는데 어떻게 객체탐색이 가능한지 이유
우선 저의 코드부터 올려보겠습니다.@Query("select m from Member m left join m.team t") List<Member> findmemberByLeftJoin();저의 코드는 JPQL에서 left join fetch를 하지 않고 left join만 걸었습니다.강의 내용에 의하면 단순 joinAll()을 하였을 때 영속성 컨텍스트로부터 proxy객체를 일단은 주입한다고 하셨습니다.저의 경우는 @Query를 활용하여 다음과 같은 JPQL을 선언하였을 때, Console에 출력되는 내용은 아래와 같습니다.left join은 걸리지만 Select절에는 Member에 대한 데이터만 불러올 뿐, Team에 대한 데이터는 불러오지 않고 있습니다.그렇다면 이때 Team을 getClass로 출력할때 proxy객체일거라 생각했습니다.하지만 직접 출력해보니 class study.datajpa.entity.Team 이렇게 출력이 됩니다.이것은 조회는 하지 않았으나, 프록시객체를 반환하지는 않고 진짜 객체로 반환한다는 뜻인데...여기서부터 햇갈리기 시작합니다.어떻게 이해하고 받아들여야 할까요?1. 쿼리상에서는 Team을 불러오지 않는데, 어떻게 객체탐색을 통해 Team 객체가 조회가 되나요?2. 쿼리상에서는 Team을 불러오지 않는데, 어째서 Proxy객체가 아닌 진짜 엔티티인가요?3. 결국 이런 현상은 패치조인과 다른 것 이라고 이해해야 할까요? (이 현상은 inner Join에서도 발생합니다) * left조인은 걸리고, select절에 team은 없지만 * n+1이 발생하지 않고도 team이 조회되는 이유 * 프록시 객체가 아닌 진짜 team객체를 반환해주는 이유