묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결김영한의 실전 자바 - 중급 1편
toCharArray 메서드 사용 후 출력 시 참조값이 나오는 현상
// toCharArray 메서드 char[] strCharArray = str.toCharArray(); System.out.println("문자열을 문자 배열로 변환: " + strCharArray); // 문자열을 문자 배열로 변환: [C@7291c18f System.out.println(strCharArray); // Hello, Java!문자열 + 상태에선 참조값이 나오고 일반 배열 출력에선 정상 출력되는데 이유를 알 수 있을까요?=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]여기에 질문 내용을 남겨주세요.
-
미해결실전! 스프링 데이터 JPA
SimpleJpaRepository 의 save() 메서드
save() 메서드 내부에서 isNew() 메서드를 통해 새로운 엔티티 여부를 확인할때 id 값이 null 인지 여부로 판단하는데만약 @GeneratedValue 의 옵션이 SEQUENCE 이면 이때에도 merge() 로 동작하는건가요?아니면 persist() 시점에서 call 을 하기 때문에 isNew() 메서드 호출 시점까지는 id 값이 null 을 유지하는 건가요?
-
미해결김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음
섹션 9, 문제와 풀이 2 질문듧니다.
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)[질문 내용]섹션 9 문제와 풀이 2의 풀이를 switch문을 안 쓰고 if 문을 써서 다음과 같이 풀었는데 맞는 걸까요?추가로, 이 문제에서 풀이로 switch문을 더 추천하는 걸까요? package method.ex; import java.util.Scanner; public class MethodEx4 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int balance = 0; while (true) { System.out.println("--------------------------------------"); System.out.println("1.입금 | 2.출금 | 3.잔액 확인 | 4.종료"); System.out.println("--------------------------------------"); System.out.print("선택: "); int choice = scanner.nextInt(); if (choice == 1) { System.out.print("입금액을 입력하세요: "); int depositAmount = scanner.nextInt(); balance = deposit(depositAmount, balance); } else if (choice == 2) { System.out.print("출금액을 입력하세요: "); int withdrawAmount = scanner.nextInt(); balance = withdraw(withdrawAmount, balance); } else if (choice == 3) { System.out.println("현재 잔액: " + balance + "원"); } else if (choice == 4) { System.out.println("시스템을 종료합니다."); break; } else { System.out.println("번호를 잘못 입력하였습니다. 다시 선택해주세요."); } } } public static int deposit(int depositAmount, int balance) { balance += depositAmount; System.out.println(depositAmount + "원을 입금하였습니다. 현재 잔액: " + balance + "원"); return balance; } public static int withdraw(int withdrawAmount, int balance) { if (balance > -withdrawAmount) { balance -= withdrawAmount; System.out.println(withdrawAmount + "원을 출금하였습니다. 현재 잔액: " + balance + "원"); } else { System.out.println(withdrawAmount + "원을 출금하려 했으나 잔액이 부족합니다."); } return balance; } }감사합니다!
-
미해결김영한의 실전 자바 - 중급 1편
내부클래스 활용 질문
학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.1. 강의 내용과 관련된 질문을 남겨주세요.2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.(자주 하는 질문 링크: https://bit.ly/3fX6ygx)3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.=========================================[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예/아니오)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)[질문 내용]여기에 질문 내용을 남겨주세요.내부 클래스 활용 8분 53초쯤에 11번째 줄 코드가this.engine = new Engine(); 이라고 나와있는데원래 Car.Engine this.engine = new Car.Engine을 생략 한 거라고 이해해도 될까요?
-
미해결자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비
LIS 관련 질문입니다.
안녕하세요.가장 높은 탑 쌓기 문제에서는 정렬을 해주었는데요! 직전 LIS 문제에서는 정렬을 따로 해주지 않았더라구요.물론 직전 문제에서 정렬을 한다면 알고리즘을 적용할 이유는 없지만, 굳이 정렬을 안 한 이유를 꼽자면 위치를 바꿀 수 없는 완성된 수열이 입력으로 들어왔다는 가정이기 때문인지 궁금합니다. 읽어주셔서 감사합니다.
-
미해결스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
스프링 데이터 jpa 통합테스트 오류
스프링 데이터 jpa의 통합테스트 - 회원가입 부분을 돌리는 부분에서 private final MemberRepository memberRepository;이 부분에서 자동 주입을 할 수 없습니다. 'MemberRepository' 타입의 bean이 두 개 이상 있습니다.라는 오류가 떠 memorymemberrepository에 쓰인 @Repository를 지워 private final MemberRepository memberRepository;이 부분의 빨간 줄은 없앴는데 테스트는 안 돌아가서 질문 남깁니다무슨 오류일까요? 해결방법도 알려주세요,,SpringConfig MemberServiceIntegrationTestSpringDataJpaMemberRepsitory아래는 테스트 실행시 나오는 에러 메시지입니다java.lang.NullPointerException: Cannot invoke "org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(java.sql.SQLException, String)" because the return value of "org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.sqlExceptionHelper()" is null at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:116) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.getJdbcEnvironmentUsingJdbcMetadata(JdbcEnvironmentInitiator.java:290) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:123) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:77) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:130) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:238) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:215) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.boot.model.relational.Database.<init>(Database.java:45) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.getDatabase(InFlightMetadataCollectorImpl.java:221) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:189) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:171) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1431) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1502) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]2024-06-21T18:39:08.309+09:00 ERROR 43820 --- [hello-spring] [ Test worker] j.LocalContainerEntityManagerFactoryBean : Failed to initialize JPA EntityManagerFactory: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] due to: Unable to determine Dialect without JDBC metadata (please set 'jakarta.persistence.jdbc.url' for common cases or 'hibernate.dialect' when a custom Dialect implementation must be provided)2024-06-21T18:39:08.310+09:00 WARN 43820 --- [hello-spring] [ Test worker] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] due to: Unable to determine Dialect without JDBC metadata (please set 'jakarta.persistence.jdbc.url' for common cases or 'hibernate.dialect' when a custom Dialect implementation must be provided)2024-06-21T18:39:08.324+09:00 INFO 43820 --- [hello-spring] [ Test worker] .s.b.a.l.ConditionEvaluationReportLogger : Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.2024-06-21T18:39:08.339+09:00 ERROR 43820 --- [hello-spring] [ Test worker] o.s.boot.SpringApplication : Application run failed
-
해결됨자바 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에서 이렇게 띄어줘 라고 설정을 해주신건가요?
-
미해결자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비
최대부분증가수열(LIS) 오답 질문
이번 강의 코드와 100% 유사한 백준 문제가 있어서 풀었는데 98%에서 오답처리 되었습니다.강사님의 강의를 이해하고 풀다보니 강의와 코드가 똑같은데 왜 오답이 나오는건가요?? https://www.acmicpc.net/problem/11053제 코드는 이렇습니다.import java.util.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr= new int[n]; for(int i=0; i<n; i++) arr[i] = sc.nextInt(); int[] dp= new int[n]; int answer=0; dp[0]=1; //solve for(int i=1; i<n; i++){ int tmp=0; for(int j=i-1; j>=0; j--){ if(arr[i] > arr[j]) tmp=Math.max(tmp, dp[j]); } dp[i]=tmp+1; answer=Math.max(answer,dp[i]); } System.out.println(answer); } }
-
해결됨실전! 스프링 부트와 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로 수정할 수 있는 로직을 넣은 거구요제가 이해한 것이 맞을까요?
-
미해결더 자바, Java 8
CompletableFuture의 get 실행에 대해 궁금한 점이 있습니다
안녕하세요.아래 코드를 실행 시키면, hello 만 출력이 되어야 될것 같은데..world 도 같이 출력이 됩니다. get() 을 하면 동일 scope 에 있는 모든 CompletableFuture 가 실행이 되는것이 맞는 건지 문의 드려요. 감사합니다. CompletableFuture<String> hello = CompletableFuture.supplyAsync( () -> { System.out.println("Hello Thread : " + Thread.currentThread().getName()); return "Hello"; } ); CompletableFuture<String> world = CompletableFuture.supplyAsync( () -> { System.out.println("World Thread : " + Thread.currentThread().getName()); return "World"; } ); hello.get();
-
미해결자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비
3.2 공통원소 구하기 에서 질문입니다.
샘플문제는 정답인데, 채점사이트에서는 오답으로 나오네요.어디가 잘못되었는지 못찾겠습니다. import java.util.*;class Main { public ArrayList<Integer> solution(int n, int[] arr1, int m, int[] arr2) {ArrayList<Integer> answer = new ArrayList<>(); Arrays.sort(arr1);Arrays.sort(arr2); int p1=0, p2=0; while(p1<n && p2<m) {if(arr1[p1]==arr2[p2]) {answer.add(arr1[p1]++);p2++;}else if(arr1[p1]<arr2[p2]) p1++;else p2++;}return answer;}
-
미해결김영한의 실전 자바 - 기본편
상속시 메모리 구조와 @Overriding 어노테이션 관련 질문 드립니다.
안녕하세요.좋은 강의 정말 재미있게 잘 수강하고 있습니다. '상속과 메서드 오버라이딩' 강의 내용 관련하여 궁금한 점이 생겨 질문 드립니다. A와 B는 강의에서 설명해주신 내용입니다. [A.상속시 메모리 구조]상속한 클래스의 메서드를 호출하는 경우에1)본인 타입에서 해당 메서드를 먼저 찾고2-1) 없으면 부모 타입에서 찾는다2-2) 있으면 종료 [B. @Overriding]자식 클래스의 메서드에 @Overriding 애노테이션을 붙여 오버라이딩 수행 시, 부모 클래스에 해당 메서드가 존재하지 않으면 컴파일 오류가 발생 그런데 여기에서 B 처럼 동작하려면 A의 2-2 경우에 자식 타입만 조사하고 종료하는 것이 아니라, 컴파일 타임에 부모 클래스의 메서드도 조사해야하지 않나요?@Overriding 애노테이션을 사용했을 때 실제로 어떤식으로 동작하는지 궁금합니다. 감사합니다.
-
미해결자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
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]
-
해결됨자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]
질문있습니다!
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
-
미해결김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음
강사님의 형변환결과값이랑 저의 형변환결과값이 다른경우...ㅠㅠ
=========================================[질문 내용]public class Casting3 { public static void main(String[] args) { long maxIntValue= 2147483647; //int 최고값 long maxIntOver= 21474836478L; //int 최고값 + 1(초과) int intValue=0; intValue = (int) maxIntValue; // 형변환 System.out.println("maxValue Casting= "+ intValue); intValue = (int) maxIntOver; //형변환 System.out.println("maxIntOver Casting = " + intValue); } } 근데 저의 결과값은 ..... 이렇게 나오는 이유가 있을까요?
-
미해결자바 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 타입)로 조회하면 크게 달라지는 코드가 있거나 주의해야하는 부분이 있는지여쭤보고 싶어서 문의글 남깁니다.