묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨입문자를 위한 Spring Boot with Kotlin - 나만의 포트폴리오 사이트 만들기
docker 빌드가 이루어지지 않고있어요 ㅜㅜ
혼자서 해결해보려고하는데 해결할수가 없네요 저런 에러만 나오고 알방법이 없어서 이렇게 질문드려요 깃허브링크까지 있어요 꼭 해결하고싶어요!!https://github.com/Minzion0/portfolio
-
해결됨실전! Querydsl
스프링 부트 2.4 이후 profile yml 설정 질문입니다.
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]여기에 질문 내용을 남겨주세요. 여태 영한님 수업을 들으면서나, 혼자서 뭔가 해보면서 오류가 나도 어떻게든 이 방법 저 방법 붙잡고 해보면 해결이 됐었는데, 스프링 공식 문서를 보고 따라해도 안되고, 구글링을 해도 안 돼서 도저히 못 하겠어서 여쭙게 되었습니다. 먼저 저의 Gradle 컴파일 시 세팅과 샘플 데이터 코드 부터 보여드리겠습니다.package study.querydsl.controller; import jakarta.annotation.PostConstruct; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import study.querydsl.entity.Member; import study.querydsl.entity.Team; @Profile("local") @Component @RequiredArgsConstructor public class InitMember { private final InitMemberService initMemberService; @PostConstruct public void init() { initMemberService.init(); } static class InitMemberService { @PersistenceContext private EntityManager em; @Transactional public void init() { Team teamA = new Team("teamA"); Team teamB = new Team("teamB"); em.persist(teamA); em.persist(teamB); for (int i = 0; i < 100; i++) { Team selectedTeam = i % 2 == 0 ? teamA : teamB; em.persist(new Member("member" + i, i, selectedTeam)); } } } }이 부분은 제가 봤을땐 문제 없는 것 같습니다. 이제 제가 yml 파일에서 시도해봤던 방법들을 보여드리겠습니다.spring: profiles: active: local --- spring: config: activate: on-profile: local --- spring: datasource: url: jdbc:h2:tcp://localhost/~/querydsl username: sa password: driver-class-name: org.h2.Driver jpa: hibernate: ddl-auto: create properties: hibernate: # show_sql: true # show_sql : `System.out` 에 하이버네이트 실행 SQL을 남긴다 format_sql: true use_sql_comments: true # 실행되는 JPQL을 볼 수 있다. logging.level: org.hibernate.SQL: debug # org.hibernate.SQL : logger를 통해 하이버네이트 실행 SQL을 남긴다. # org.hibernate.type: trace # SQL 실행 파라미터를 로그로 남긴다.첫 번째로 시도했던 방법입니다. application.yml입니다. 아래에 오류 첨부 하겠습니다. Execution failed for task ':QuerydslApplication.main()'.> Process 'command '/Users/idohyeon/Library/Java/JavaVirtualMachines/corretto-17.0.11/Contents/Home/bin/java'' finished with non-zero exit value 1* Try:> Run with --stacktrace option to get the stack trace.> Run with --info or --debug option to get more log output.> Run with --scan to get full insights.> Get more help at https://help.gradle.org.Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.For more on this, please refer to https://docs.gradle.org/8.8/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.BUILD FAILED in 2s3 actionable tasks: 2 executed, 1 up-to-date 첫 번째 방법 시도시 오류 입니다.두 번째 방법 입니다.#spring: # profiles: # active: local #--- spring: config: activate: on-profile: local --- spring: datasource: url: jdbc:h2:tcp://localhost/~/querydsl username: sa password: driver-class-name: org.h2.Driver jpa: hibernate: ddl-auto: create properties: hibernate: # show_sql: true # show_sql : `System.out` 에 하이버네이트 실행 SQL을 남긴다 format_sql: true use_sql_comments: true # 실행되는 JPQL을 볼 수 있다. logging.level: org.hibernate.SQL: debug # org.hibernate.SQL : logger를 통해 하이버네이트 실행 SQL을 남긴다. # org.hibernate.type: trace # SQL 실행 파라미터를 로그로 남긴다.application.yml입니다. 알아보니 스프링 부트 2.4부터는 spring.profiles로 설정하면 안되고spring.config.activate.on-profile로 설정해야 된다고 해서 맨 위 spring.profiles.active 이 부분 빼고 해보았습니다.그래도 되지 않습니다. 하지만 그래도 이때는 정상적으로 실행이 되긴 하지만 profile이 먹히지 않아 샘플 데이터들이 insert 나가지도 않고,디비에도 들어와 있지 않습니다.세 번째 방법 입니다. spring: config.activate.on-profile: localapplication-local.yml 파일을 위와 같이 만들어둔 상태에서 첫 번째 방법, 두 번째 방법을 시도해봤는데 둘 다 첫 번째 방법 때와 같은 오류가 발생합니다.https://docs.spring.io/spring-boot/reference/features/profiles.html#page-title마지막으로 이번엔 공식 문서를 보고 따라해봤던 방법입니다. 이 방법까지 해봤는데도 해결이 되지 않습니다.
-
해결됨Practical Testing: 실용적인 테스트 가이드
테스트 대상
학습 관련 질문을 남겨주세요. 어떤 부분이 고민인지, 무엇이 문제인지 상세히 작성하면 더 좋아요!먼저 유사한 질문이 있었는지 검색해 보세요.서로 예의를 지키며 존중하는 문화를 만들어가요. 안녕하세요 강사님강의 13분초 쯤 productType에 대해 test를 하시는데 이 때 HANDMADE와 BAKERY에 대해서만 테스트를 진행하셨는데 BOTTLE에 대해서는 안해도 될까요?? 실무에서는 어떻게 하는 지 궁금합니다. 뭔가 추가해주어야 할 거 같아서요!
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
JPA
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]@Table 설정하면 insert문이 나가면서 jpa 실행 시간에 영향을 준다고 하셨는데 insert문 없이 create만 나가서요 이것도 jpa 실행 시간에 영향을 안주는 거 아닌가요??
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
후하 제머리로는 좀 어렵네요 mysql 설치
mysql 설치가 커뮤니티보고 다해봐도 다안돼네요 ㅠㅠ혹시 2024년 버전 해결방안 있나요?
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
git 질문있습니다.
강의내용 7:31초.gitignore 파일을 만들떄 자동저장 or 수도저장 할건지 물어보는 부분에서 don't ask again 클릭후 add으로 눌러버려서 수동으로 저장으로 다시 바꾸고 싶은데 어떻게 해야하나요?죄송해요 구글링해도 안나와서 이런 사소한 질문 죄송합니다!
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
h2 데이타베이스 연결 문제
Database "mem:library" not found, either pre-create it or allow remote database creation (not recommended in secure environments)이런 식으로 mem:library 를찾을수없다고 뜹니다 무엇이문제일까요?구굴링해도 안뜹니다 혹시 h2 데이타베이스를 설치해야하는건가요?
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
user 오류
NON_KEYWORDS=USER을 추가해도 이렇게 뜨는데 어떻게 해야할까요?
-
미해결실전! 스프링 데이터 JPA
SimpleJpaRepository 의 save() 메서드
save() 메서드 내부에서 isNew() 메서드를 통해 새로운 엔티티 여부를 확인할때 id 값이 null 인지 여부로 판단하는데만약 @GeneratedValue 의 옵션이 SEQUENCE 이면 이때에도 merge() 로 동작하는건가요?아니면 persist() 시점에서 call 을 하기 때문에 isNew() 메서드 호출 시점까지는 id 값이 null 을 유지하는 건가요?
-
해결됨자바 ORM 표준 JPA 프로그래밍 - 기본편
from절의 서브쿼리 테스트 문제
[질문 내용]하이버네이트 6에서 from절의 서브 쿼리 테스트 위해 다음과 같은 쿼리를 작성해서 실행 했는데, 쿼리가 날아가지 않습니다. 잘못된 부분이 있을까요?
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
궁금한게 또 있습니다!!
강의 04:40초 부분인데요 public void saveUser(UserCreateRequest request) { User u = userRepository.save(new User(request.getName(), request.getAge())); throw new IllegalArgumentException(); }이부분에서 예외를 주고 서버를 띄어서 확인을 했는데저렇게 "서버 내부 오류입니다" 라고 뜨는 것은 예외를 던져주면 자동으로 저렇게 뜨게 설정되어있는 건가요?아니면 이렇게 예외를 던지면 ui에서 이렇게 띄어줘 라고 설정을 해주신건가요?
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
itemRepository MemberRepository에 save메서드
[질문 내용]여기에 질문 내용을 남겨주세요.둘다 save 메서드가 있는데itemRepository 에서 save와 MemberRepository save에서 저장을 하게되면 아직 db에 insert를 한게 아니기 때문에 item이나 member은 id값은 먼저 null인 상태에서 메서드에 들어가고 em.persist을 하게되면 member은 바로 db에 들어가 id를 부여 받고 item도 당연히 null이니까 db에 들어가 id를 부여 받는 것이죠? member은 수정할 일이 없는데 item은 수정할 일이 있기 때문에 item의 id값이 있으면 em.merge로 수정할 수 있는 로직을 넣은 거구요제가 이해한 것이 맞을까요?
-
미해결
JPA @Query 로는 동적쿼리 작성은 불가능한가요?
QueryDSL로는 구현이 어려워, 네이티브 쿼리를 작성하려고 합니다.그런데, where 조건을 동적으로 작성해야하는데... @Query의 경우 동적쿼리가 불가능한가요?
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
D-Day 앱 만들기에서 에러가 나옵니다ㅠㅠ
하나는 "NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null" 이런 에러인거 같은데....대체 어디서 잘못된걸까요. 에러가 여러개 인건가요?FAILURE: Build completed with 2 failures.1: Task failed with an exception.-----------* What went wrong:Execution failed for task ':app:checkDebugAarMetadata'.> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction > 5 issues were found when checking AAR metadata:* Try:> Run with --info or --debug option to get more log output.> Run with --scan to get full insights.* Exception is:org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:checkDebugAarMetadata'. Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction Caused by: java.lang.RuntimeException: 5 issues were found when checking AAR metadata: 1. Dependency 'androidx.appcompat:appcompat-resources:1.7.0' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs. :app is currently compiled against android-33. Also, the maximum recommended compile SDK version for Android Gradle plugin 8.0.0 is 33. Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdk of at least 34. Note that updating a library or application's compileSdk (which allows newer APIs to be used) can be done separately from updating targetSdk (which opts the app in to new runtime behavior) and minSdk (which determines which devices the app can be installed on). 2. Dependency 'androidx.appcompat:appcompat:1.7.0' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs. :app is currently compiled against android-33. Also, the maximum recommended compile SDK version for Android Gradle plugin 8.0.0 is 33. Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdk of at least 34. Note that updating a library or application's compileSdk (which allows newer APIs to be used) can be done separately from updating targetSdk (which opts the app in to new runtime behavior) and minSdk (which determines which devices the app can be installed on). 3. Dependency 'androidx.core:core-ktx:1.13.0' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs. :app is currently compiled against android-33. Also, the maximum recommended compile SDK version for Android Gradle plugin 8.0.0 is 33. Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdk of at least 34. Note that updating a library or application's compileSdk (which allows newer APIs to be used) can be done separately from updating targetSdk (which opts the app in to new runtime behavior) and minSdk (which determines which devices the app can be installed on). 4. Dependency 'androidx.core:core:1.13.0' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs. :app is currently compiled against android-33. Also, the maximum recommended compile SDK version for Android Gradle plugin 8.0.0 is 33. Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdk of at least 34. Note that updating a library or application's compileSdk (which allows newer APIs to be used) can be done separately from updating targetSdk (which opts the app in to new runtime behavior) and minSdk (which determines which devices the app can be installed on). 5. Dependency 'androidx.annotation:annotation-experimental:1.4.0' requires libraries and applications that depend on it to compile against version 34 or later of the Android APIs. :app is currently compiled against android-33. Also, the maximum recommended compile SDK version for Android Gradle plugin 8.0.0 is 33. Recommended action: Update this project's version of the Android Gradle plugin to one that supports 34, then update this project to use compileSdk of at least 34. Note that updating a library or application's compileSdk (which allows newer APIs to be used) can be done separately from updating targetSdk (which opts the app in to new runtime behavior) and minSdk (which determines which devices the app can be installed on). ==============================================================================2: Task failed with an exception.-----------* What went wrong:Execution failed for task ':app:mergeExtDexDebug'.> Could not resolve all files for configuration ':app:debugRuntimeClasspath'. > Failed to transform appcompat-resources-1.7.0.aar (androidx.appcompat:appcompat-resources:1.7.0) to match attributes {artifactType=android-dex, asm-transformed-variant=NONE, dexing-enable-desugaring=true, dexing-enable-jacoco-instrumentation=false, dexing-is-debuggable=true, dexing-min-sdk=24, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}. > Execution failed for DexingNoClasspathTransform: C:\Users\abc14\.gradle\caches\transforms-3\c494794d48d9429ce3837ff3d9162578\transformed\appcompat-resources-1.7.0-runtime.jar. > Error while dexing. > Failed to transform appcompat-1.7.0.aar (androidx.appcompat:appcompat:1.7.0) to match attributes {artifactType=android-dex, asm-transformed-variant=NONE, dexing-enable-desugaring=true, dexing-enable-jacoco-instrumentation=false, dexing-is-debuggable=true, dexing-min-sdk=24, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}. > Execution failed for DexingNoClasspathTransform: C:\Users\abc14\.gradle\caches\transforms-3\d251d80cfc588f74172158875c7b2196\transformed\appcompat-1.7.0-runtime.jar. > Error while dexing.* Try:> Run with --info or --debug option to get more log output.> Run with --scan to get full insights.* Exception is:org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeExtDexDebug'. Caused by: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null Caused by: java.util.concurrent.ExecutionException: com.android.tools.r8.utils.P0: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null Caused by: [CIRCULAR REFERENCE: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null]Cause 2: org.gradle.api.internal.artifacts.transform.TransformException: Failed to transform appcompat-1.7.0.aar (androidx.appcompat:appcompat:1.7.0) to match attributes {artifactType=android-dex, asm-transformed-variant=NONE, dexing-enable-desugaring=true, dexing-enable-jacoco-instrumentation=false, dexing-is-debuggable=true, dexing-min-sdk=24, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}. Caused by: org.gradle.api.internal.artifacts.transform.TransformException: Execution failed for DexingNoClasspathTransform: C:\Users\abc14\.gradle\caches\transforms-3\d251d80cfc588f74172158875c7b2196\transformed\appcompat-1.7.0-runtime.jar. Caused by: com.android.builder.dexing.DexArchiveBuilderException: Error while dexing. at com.android.builder.dexing.D8DexArchiveBuilder.getExceptionToRethrow(D8DexArchiveBuilder.java:189) Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete, origin: C:\Users\abc14\.gradle\caches\transforms-3\d251d80cfc588f74172158875c7b2196\transformed\appcompat-1.7.0-runtime.jar:androidx/appcompat/app/ActionBarDrawerToggle$1.class Caused by: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null Suppressed: java.lang.RuntimeException: java.util.concurrent.ExecutionException: com.android.tools.r8.utils.P0: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null Caused by: java.util.concurrent.ExecutionException: com.android.tools.r8.utils.P0: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null Caused by: com.android.tools.r8.utils.P0: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null Caused by: [CIRCULAR REFERENCE: java.lang.NullPointerException: Cannot invoke "String.length()" because "<parameter1>" is null]
-
미해결
QueryDSL 에서 중복된 데이터를 제거하고, 집계함수(count, sum 등)을 적용하는 방법에 대해 조언 구합니다!
JOIN으로 인해서, 아래와 같이 중복되는 데이터가 발생했습니다.id | price1 50001 50002 60002 6000따라서, Distinct를 통해 아래와 같이 중복데이터를 제외하고, groupBy(id)를 통해 id별로 price의 sum을 구해야 합니다.id | price1 50002 6000이를 쿼리로 짜야한다면... JOIN 이후 Distinct를 적용한 서브쿼리를 From으로 조회해서 다시 groupBy(id) 를 통해 price의 sum을 구해야하는데요...위와 같이, subquery를 from 으로 조회해야 한다면... QueryDSL 을 통해 subquery를 from으로 조회하는 문법과 관련한 내내용을 아시는 분 계실까요 ㅠ(링크라도 부탁드립니다 ㅠ)아니면 혹시 다른 방법이 있을까요?- 본래 집계함(count, sum 등)수와 distinct 를 동시에 사용할 수 있는 것으로 압니다. 그런데 QueryDSL의 경우 countDistinct() 는 존재하는데... sumDisctinct()는 없는 것 같더라고요. 선배님들의 도움 절실히 부탁드립니다 ㅠ
-
해결됨자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
질문있습니다!
10:49초 에 질문이 있습니다.userRepository.findById(request.getId()) 를 하면 왜 optional<User>가 나오는 건지 알수있나요?
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
insert로그 확인 후 h2 db에 값이 안나옵니다..
[질문 내용]여기에 질문 내용을 남겨주세요.강의 11분쯤insert 로그 확인 후 h2 db에 들어가 값이 들어가는지 확인을 하는데요저도 로그에서 insert문 확인 후 h2 db에 들어 갔는데 값이계속 안 나와 질문 올립니다. 밑에는 로그 내역이고 구글 드라이브 링크도 같이 올립니다.2024-06-20T21:12:05.260+09:00 DEBUG 21664 --- [ Test worker] org.hibernate.SQL : select m1_0.member_id, m1_0.city, m1_0.street, m1_0.zipcode, m1_0.name from member m1_0 where m1_0.name=? 2024-06-20T21:12:05.276+09:00 INFO 21664 --- [ Test worker] p6spy : #1718885525275 | took 7ms | statement | connection 3| url jdbc:h2:mem:7cd22d26-ead4-4150-987b-79b62bd18ed5 select m1_0.member_id,m1_0.city,m1_0.street,m1_0.zipcode,m1_0.name from member m1_0 where m1_0.name=? select m1_0.member_id,m1_0.city,m1_0.street,m1_0.zipcode,m1_0.name from member m1_0 where m1_0.name='kim'; 2024-06-20T21:12:05.289+09:00 DEBUG 21664 --- [ Test worker] org.hibernate.SQL : select next value for member_seq 2024-06-20T21:12:05.292+09:00 INFO 21664 --- [ Test worker] p6spy : #1718885525292 | took 1ms | statement | connection 3| url jdbc:h2:mem:7cd22d26-ead4-4150-987b-79b62bd18ed5 select next value for member_seq select next value for member_seq; 2024-06-20T21:12:05.336+09:00 DEBUG 21664 --- [ Test worker] org.hibernate.SQL : insert into member (city, street, zipcode, name, member_id) values (?, ?, ?, ?, ?) 2024-06-20T21:12:05.340+09:00 INFO 21664 --- [ Test worker] p6spy : #1718885525340 | took 0ms | statement | connection 3| url jdbc:h2:mem:7cd22d26-ead4-4150-987b-79b62bd18ed5 insert into member (city,street,zipcode,name,member_id) values (?,?,?,?,?) insert into member (city,street,zipcode,name,member_id) values (NULL,NULL,NULL,'kim',1); 2024-06-20T21:12:05.345+09:00 INFO 21664 --- [ Test worker] p6spy : #1718885525345 | took 0ms | commit | connection 3| url jdbc:h2:mem:7cd22d26-ead4-4150-987b-79b62bd18ed5 ; 혼자 해결을 하고 싶었는데 가망이 없어 질문 올립니다..부탁드립니다!!ㅠㅠㅠㅠㅠhttps://drive.google.com/file/d/1k4Dsk8P3O2Ofm0Ab-CyVTA98aN-66p1_/view?usp=drive_link
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
상속관계 Joined - 임시 테이블로 생성/삭제로 인한 성능 문제
안녕하세요 영한님.상속관계 Joined 매핑을 사용할 때, 부모테이블에 대하여 업데이트 쿼리 시 임시 테이블 Create Drop 에 대해 질문드리고 싶습니다. 최근에 플젝을 진행하면서 JPA 상속관계 Joined 전략을 활용했는데요, 프로젝트 초기에는 정규화된 테이블 구조로 먼저 진행하고, 추후 성능 이슈가 발생하면 단일 테이블 전략으로 역 정규화를 논의하는 것이 나을 것으로 판단했기 때문입니다.Domain// 부모 엔티티 @Entity @DiscriminatorColumn @Inheritance(strategy = InheritanceType.JOINED) public class Notification { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "notification_id") private Long id; @Enumerated(value = EnumType.STRING) @Column(nullable = false, columnDefinition = "varchar(50)") private NotificationEventType notificationEventType; @Column(nullable = false) private LocalDateTime createdAt; @Column(name = "\"read\"", nullable = false) private Boolean read; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", nullable = false) private User notifier; }// 자식 엔티티 @Entity public class RecruitmentNotification extends Notification { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "recruitment_id", nullable = false) private Recruitment actor; } @Entity public class StudyNotification extends Notification { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "study_id", nullable = false) private Study actor; } @Entity public class ReviewNotification extends Notification { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "review_id", nullable = false) private Review actor; } Service@Service @RequiredArgsConstructor @Slf4j public class NotificationCommandService { private final NotificationRepositoryImpl notificationRepository; public void updateNotificationsAsRead(final User user, final List<Long> notificationIds) { notificationRepository.updateNotificationsAsRead(user.getId(), notificationIds); } } Repositorypublic interface NotificationJpaRepository extends JpaRepository<Notification, Long> { @Modifying @Query("UPDATE Notification n " + "SET n.read = true " + "WHERE n.notifier.id = :userId AND n.id IN :notificationIds") void updateNotificationsAsRead(final Long userId, final List<Long> notificationIds); } @Repository @RequiredArgsConstructor public class NotificationRepositoryImpl { private final JPAQueryFactory q; private final NotificationJpaRepository notificationJpaRepository; private final EntityManager em; public void updateNotificationsAsRead(final Long userId, final List<Long> notificationIds) { notificationJpaRepository.updateNotificationsAsRead(userId, notificationIds); em.flush(); em.clear(); } } 부모테이블에 대하여 업데이트 쿼리 시, JPA 구현체가 자체적으로 임시 테이블을 Create 및 Drop 하는 로그를 확인했습니다.create temporary table if not exists HT_notification(notification_id bigint not null, primary key (notification_id)) drop temporary table HT_notification 두 가지 문제점이 있다고 생각하는데요.보안 이슈 등을 고려하여, 현재 상용 DB 의 백엔드 사용자 권한에 DDL을 제외하였습니다.이에 따라 임시 테이블을 생성하지 못하고, 500 에러가 발생하는 상황입니다.JPA 상속 관계 매핑 전략만을 위해 DB 사용자 권한을 넓게 가져가는 것이 올바른지 잘 모르겠습니다 🤔 업데이트 API를 호출할 때마다, 임시 테이블을 생성하고 드랍하는 행위가 매우 비효율적이라 생각되는데,이럴 경우 Single 테이블 전략으로 수정하거나, 상속관계 매핑 자체를 안쓰는 방법밖엔 없을까요?상속관계 매핑 전략은 애플리케이션 레벨에서 DB 테이블의 조작을 손쉽게하는 장점이 있긴하지만,결국 상용 서비스 중인 DB를 세팅할 땐 데이터베이스 레벨에서 DDL을 직접 세팅하는게 좋고, 기존의 장점이 상쇄되는 느낌입니다.성능적 손해를 감수하면서도 상속 관계 매핑을 활용하는게 좋은 접근 방법인지 판단이 서지 않아 질문드립니다 🙂
-
미해결자바 ORM 표준 JPA 프로그래밍 - 기본편
상속관계 Joined 매핑 - 임시 테이블 Create Drop에 관하여
안녕하세요 영한님.상속관계 Joined 매핑을 사용할 때, 부모테이블에 대하여 업데이트 쿼리 시 임시 테이블 Create Drop 에 대해 질문드리고 싶습니다. 최근에 플젝을 진행하면서 JPA 상속관계 Joined 전략을 활용했습니다.부모테이블에 대하여 업데이트 쿼리 시, JPA 구현체가 자체적으로 임시 테이블을 Create 및 Drop 하는 로그를 확인했습니다. Domain// 부모 엔티티 @Entity @DiscriminatorColumn @Inheritance(strategy = InheritanceType.JOINED) public class Notification { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "notification_id") private Long id; @Enumerated(value = EnumType.STRING) @Column(nullable = false, columnDefinition = "varchar(50)") private NotificationEventType notificationEventType; @Column(nullable = false) private LocalDateTime createdAt; @Column(name = "\"read\"", nullable = false) private Boolean read; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", nullable = false) private User notifier; }// 자식 엔티티 @Entity public class RecruitmentNotification extends Notification { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "recruitment_id", nullable = false) private Recruitment actor; } @Entity public class StudyNotification extends Notification { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "study_id", nullable = false) private Study actor; } @Entity public class ReviewNotification extends Notification { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "review_id", nullable = false) private Review actor; } Service@Service @RequiredArgsConstructor @Slf4j public class NotificationCommandService { private final NotificationRepositoryImpl notificationRepository; public void updateNotificationsAsRead(final User user, final List<Long> notificationIds) { notificationRepository.updateNotificationsAsRead(user.getId(), notificationIds); } } Repositorypublic interface NotificationJpaRepository extends JpaRepository<Notification, Long> { @Modifying @Query("UPDATE Notification n " + "SET n.read = true " + "WHERE n.notifier.id = :userId AND n.id IN :notificationIds") void updateNotificationsAsRead(final Long userId, final List<Long> notificationIds); } @Repository @RequiredArgsConstructor public class NotificationRepositoryImpl { private final JPAQueryFactory q; private final NotificationJpaRepository notificationJpaRepository; private final EntityManager em; public void updateNotificationsAsRead(final Long userId, final List<Long> notificationIds) { notificationJpaRepository.updateNotificationsAsRead(userId, notificationIds); em.flush(); em.clear(); } } 업데이트 API를 호출할 때마다, 임시 테이블을 생성하고 드랍하는 행위가 매우 비효율적이라 생각되는데,이럴 경우 Single 테이블 전략으로 수정하거나, 상속관계 매핑 자체를 안쓰는 방법밖엔 없을까요? 상속관계 매핑 전략은 애플리케이션 레벨에서 DB 테이블의 조작을 손쉽게하는 장점이 있긴하지만,결국 상용 서비스 중인 DB를 세팅할 땐 데이터베이스 레벨에서 DDL을 직접 세팅하는게 좋고, 기존의 장점이 상쇄되는 느낌입니다.성능적 손해를 감수하면서도 상속 관계 매핑을 활용하는게 좋은 접근 방법인지 판단이 서지 않아 질문드립니다 🙂
-
해결됨자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
Id 대신 name을 사용하는 이유
강의에서 사용자는 Id로 조회하고, 도서는 name으로 조회하는데 별도의 이유가 있을까요?실제 구현한다면 동일한 도서명이 있을 것 같기도 하고, 일관성을 위해 강의를 참고하며개인적으로 두가지 다 Id로 조회하도록 구현하고 있었습니다. Dto나 Repository 등에서 타입과 이름만 잘 변경해주면 문제가 없을꺼라고 생각했는데중간에 제가 잘못 설계한 곳이 있는지 도서 대출시 BookRequestLoan에 값이 계속 안넘어옵니다. 혹시 Id (long 타입)로 조회하면 크게 달라지는 코드가 있거나 주의해야하는 부분이 있는지여쭤보고 싶어서 문의글 남깁니다.