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

moonseok.shin님의 프로필 이미지
moonseok.shin

작성한 질문수

실전! Querydsl

스프링 부트 설정 - JPA, DB

unit Test 는 성공했다고 나옵니다만, h2 콘솔에서 Hello table 이 생성되지 않았습니다.

작성

·

760

0

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.

1. 강의 내용과 관련된 질문을 남겨주세요.
2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.
(자주 하는 질문 링크: https://bit.ly/3fX6ygx)
3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.
(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)

질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.
=========================================
[질문 템플릿]
1. 강의 내용과 관련된 질문인가요? (예/아니오)
2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)
3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)

[질문 내용]
여기에 질문 내용을 남겨주세요.

unit Test 는 성공했다고 나옵니다만, h2 콘솔에서 Hello

table 이 생성되지 않았습니다.

build.gradle

plugins {
   id 'org.springframework.boot' version '2.2.2.RELEASE'
   id 'io.spring.dependency-management' version '1.0.8.RELEASE' //querydsl 추가
   id "com.ewerk.gradle.plugins.querydsl" version "1.0.10"
   id 'java'
}
group = 'study'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
   compileOnly {
      extendsFrom annotationProcessor
   }
}
repositories {
   mavenCentral()
}
dependencies {
   implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
   implementation 'org.springframework.boot:spring-boot-starter-web'
   //querydsl 추가
   implementation 'com.querydsl:querydsl-jpa'
   implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0'

   compileOnly 'org.projectlombok:lombok'
   runtimeOnly 'com.h2database:h2'
   annotationProcessor 'org.projectlombok:lombok'
   testImplementation('org.springframework.boot:spring-boot-starter-test') {
      exclude group: 'org.junit.vintage',  module: 'junit-vintage-engine'
   }

}
test {
   useJUnitPlatform()
}
//querydsl 추가 시작
def querydslDir = "$buildDir/generated/querydsl"
querydsl {
   jpa = true
   querydslSourcesDir = querydslDir
}
sourceSets {
   main.java.srcDir querydslDir
}
configurations {
   querydsl.extendsFrom compileClasspath
}
compileQuerydsl {
   options.annotationProcessorPath = configurations.querydsl
}
//querydsl 추가 끝

application.yml

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
      format_sql: true
logging.level:
  org.hibernate.SQL: debug
  ord.hibernate.type: trace

h2 z콘솔 -> 테이블 안 보임.

 jdbc:h2:tcp://localhost/~/querydsl
 INFORMATION_SCHEMA
 사용자
 H2 2.1.214 (2022-06-13)

 

select * from hello 를 해도

Table "HELLO" not found (this database is empty); SQL statement:
select from HELLO [42104-214]
42S04/42104 (도움말)
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "HELLO" not found (this database is empty); SQL statement:
select
from HELLO [42104-214]

unitTest 는 정상적입니다.

package study.querydsl;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import study.querydsl.entity.Hello;
import study.querydsl.entity.QHello;

import javax.persistence.EntityManager;

import static org.assertj.core.api.Assertions.*;

@SpringBootTest
@Transactional
@Rollback(value = false)
class QuerydslApplicationTests {
   @Autowired
   EntityManager em;

   @Test
   void contextLoads() {
      Hello hello = new Hello();

      em.persist(hello);

      JPAQueryFactory query = new JPAQueryFactory(em);
      QHello qHello = QHello.hello;

      Hello result = query.selectFrom(qHello).fetchOne();
      assertThat(result).isEqualTo(hello);
      assertThat(result.getId()).isEqualTo(hello.getId());
   }
}

답변 3

0

moonseok.shin님의 프로필 이미지
moonseok.shin
질문자

h2 를 2.1.214 버전을 제거 하고,

1.4.199 버젼으로 다운그레이드 하여 성공하였습니다.
지난번 다른 수업에서는 1.4.199 는 실패하고, 2.1.214 만 성공했었는데, 어렵네요.

0

moonseok.shin님의 프로필 이미지
moonseok.shin
질문자

들여 쓰기를 같이 하여 테스트 해 보았습니다.

실행해 봤는데, h2 를 끄면 오류를 내고 h2 를 켰을 때 오류를 내지 않는 것으로 봐서 정상 연결한 것 같은데, 테스트 시작시 연결로그도 없네요.

아래와 같이 나오고 h2 콘솔에서는 hello 테이블이 추가되지 않습니다.

 

2023-05-07 19:21:57.872 INFO 17015 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...

2023-05-07 19:21:57.946 INFO 17015 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.

2023-05-07 19:21:58.006 INFO 17015 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]

2023-05-07 19:21:58.067 INFO 17015 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.4.9.Final}

2023-05-07 19:21:58.260 INFO 17015 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}

2023-05-07 19:21:58.407 INFO 17015 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect

2023-05-07 19:21:59.091 DEBUG 17015 --- [ main] org.hibernate.SQL : drop table hello if exists

2023-05-07 19:21:59.095 DEBUG 17015 --- [ main] org.hibernate.SQL : drop table member if exists

2023-05-07 19:21:59.096 DEBUG 17015 --- [ main] org.hibernate.SQL : drop table team if exists

2023-05-07 19:21:59.097 DEBUG 17015 --- [ main] org.hibernate.SQL : drop sequence if exists hibernate_sequence

2023-05-07 19:21:59.100 DEBUG 17015 --- [ main] org.hibernate.SQL : create sequence hibernate_sequence start with 1 increment by 1

2023-05-07 19:21:59.103 DEBUG 17015 --- [ main] org.hibernate.SQL : create table hello (id bigint not null, primary key (id))

2023-05-07 19:21:59.105 DEBUG 17015 --- [ 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))

2023-05-07 19:21:59.107 DEBUG 17015 --- [ main] org.hibernate.SQL : create table team (team_id bigint not null, name varchar(255), primary key (team_id))

2023-05-07 19:21:59.110 DEBUG 17015 --- [ main] org.hibernate.SQL : alter table member add constraint FKcjte2jn9pvo9ud2hyfgwcja0k foreign key (team_id) references team

2023-05-07 19:21:59.115 INFO 17015 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

2023-05-07 19:21:59.121 INFO 17015 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'

2023-05-07 19:21:59.349 WARN 17015 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

2023-05-07 19:21:59.547 INFO 17015 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'

2023-05-07 19:21:59.806 INFO 17015 --- [ main] study.querydsl.QuerydslApplicationTests : Started QuerydslApplicationTests in 8.197 seconds (JVM running for 8.992)

2023-05-07 19:21:59.891 INFO 17015 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@3e62d773 testClass = QuerydslApplicationTests, testInstance = study.querydsl.QuerydslApplicationTests@796fe2b5, testMethod = contextLoads@QuerydslApplicationTests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4ef74c30 testClass = QuerydslApplicationTests, locations = '{}', classes = '{class study.querydsl.QuerydslApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7dcf94f8, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@f5958c9, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5bda8e08, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@3d285d7e], 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]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@1031c1a0]; rollback [false]

2023-05-07 19:21:59.978 DEBUG 17015 --- [ main] org.hibernate.SQL : call next value for hibernate_sequence

2023-05-07 19:22:00.180 DEBUG 17015 --- [ main] org.hibernate.SQL : insert into hello (id) values (?)

2023-05-07 19:22:00.185 DEBUG 17015 --- [ main] org.hibernate.SQL : select hello0_.id as id1_0_ from hello hello0_

2023-05-07 19:22:00.246 INFO 17015 --- [ main] o.s.t.c.transaction.TransactionContext : Committed transaction for test: [DefaultTestContext@3e62d773 testClass = QuerydslApplicationTests, testInstance = study.querydsl.QuerydslApplicationTests@796fe2b5, testMethod = contextLoads@QuerydslApplicationTests, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4ef74c30 testClass = QuerydslApplicationTests, locations = '{}', classes = '{class study.querydsl.QuerydslApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7dcf94f8, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@f5958c9, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5bda8e08, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@3d285d7e], 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]]

2023-05-07 19:22:00.255 INFO 17015 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

2023-05-07 19:22:00.255 INFO 17015 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

2023-05-07 19:22:00.256 INFO 17015 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'

2023-05-07 19:22:00.256 DEBUG 17015 --- [extShutdownHook] org.hibernate.SQL : drop table hello if exists

2023-05-07 19:22:00.258 DEBUG 17015 --- [extShutdownHook] org.hibernate.SQL : drop table member if exists

2023-05-07 19:22:00.260 DEBUG 17015 --- [extShutdownHook] org.hibernate.SQL : drop table team if exists

2023-05-07 19:22:00.262 DEBUG 17015 --- [extShutdownHook] org.hibernate.SQL : drop sequence if exists hibernate_sequence

2023-05-07 19:22:00.264 INFO 17015 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...

2023-05-07 19:22:09.295 INFO 17015 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

 

0

moonseok.shin님의 프로필 이미지
moonseok.shin
질문자

p6spy 도 적용 안되는 것 같습니다.

DB 관련해서는 혹시 들여쓰기가 잘못되서 그런건 아닐까요?

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
        format_sql: true

테스트 시작될 때 로그 보시면 연결 정보 보실 수 있어요

HikariPool-1 - Added connection conn0: url=jdbc:h2:tcp://localhost/~/querydsl

이렇게 떠야 datasource 설정이 적용된것입니다

HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:59f5d822-a6d6-40fc-b3f3-8d9293664716

이런 식으로 뜨면 datasource를 찾지 못한거에요

테스트 할 때 datasource를 찾지 못하면 스프링부트가 임베디드 모드로(jdbc:h2:mem:XXXXX) 동작하는데 그래서 테스트는 정상적으로 성공했을 수 있어요

moonseok.shin님의 프로필 이미지
moonseok.shin

작성한 질문수

질문하기