반응형

Spring Boot QueryDSL 초기 설정

Quesrydsl 을 사용하기 위해서는 SpringDataJPA도 추가해야 함

build.gradle 설정 추가

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'

	// H2 Database
	runtimeOnly 'com.h2database:h2'

	// QueryDSL
	implementation 'com.querydsl:querydsl-jpa:5.0.0'
	annotationProcessor "com.querydsl:querydsl-apt:5.0.0:jpa"    // querydsl JPAAnnotationProcessor 사용 지정
	annotationProcessor "jakarta.persistence:jakarta.persistence-api"	// java.lang.NoClassDefFoundError(javax.annotation.Entity) 발생 대응
	annotationProcessor "jakarta.annotation:jakarta.annotation-api"		// java.lang.NoClassDefFoundError (javax.annotation.Generated) 발생 대응
	
}

/** clean 태스크 실행시 QClass 삭제 */
clean {
	delete file('src/main/generated') // 인텔리제이 Annotation processor 생성물 생성위치
}

IntelliJ에서 프로젝트 실행시, 엔티티 클래스 앞에 Q가 붙은 Q클래스가 생성이 되는데 이는 IntelliJ 설정에 따라 생성되는 위치가 다르다.

IntelliJ IDEA에서 빌드방식 선택(Gradle or IntelliJ IDEA에 따라 ‘Querydsl Annotation processor’ 가 생성하는 Q클래스의 위치가 달라지기 때문이다.

Gradle 로 설정시

  • Qclass 생성경로: build/generated/sources/annotationProcessor/java/main
  • Q클래스에 대한 별도 정리 작업 없이 Clean태스크로 정리 된다.

IntelliJ IDEA로 설정시

  • Qclass 생성경로: src/main/generated
  • Compiler Annotation procesoors 설정영향받음
  • 기존 생성된 Q클래스는 갱신되지만 엔티티 위치 변경이나 삭제된 경우 기존Q클래스는 그대로 유지된다
  • src/main/generated 폴더에 생성된 Q클래스 처리 태스크를 작성 해야 한다.

  • IntelliJ IDE 설정으로 사용시 github로 버전관리를 하면 generated 경로 파일이 올라가지 않도록 .gitignore에 추가해주도록 하자. (generated)

[참고자료]

https://gaemi606.tistory.com/entry/Spring-Boot-Querydsl-추가-Gradle-7x

http://honeymon.io/tech/2020/07/09/gradle-annotation-processor-with-querydsl.html

반응형

SpringBoot에서 jpa를 사용하여 Entity를 생성시에 @Entity 어노테이션을 사용하여 DDL이 자동으로 생성되도록 설정을 하였고

초기 데이터 적재를 위해 resource 디렉토리 아래 data.sql 파일에 insert 문을 넣고 실행시 아래 에러가 발생했다.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/Users/guda/dev/SpringBoot/workspace/demo/out/production/resources/data.sql]: INSERT INTO book (`title`, `author`, `price`) VALUES ('지금 이대로 좋다', '법류 저', 9330); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "BOOK" not found; SQL statement:

처음 공부하는 환경에서 하다 보니 하루동안 삽질 하면서 어떤 문제인지 엄청 삽질을 했다

실행환경 SpringBoot(2.6.4) + Gradle(7.4) + H2(database 2.1.4) + JPA(2.6.4)

결론은 스프링 2.5부터 SQL Script DataSource Initialization이 변경되면서 발생된 문제였다.
schema.sql 및 data.sql 스크립트를 지원하는 데 사용되는 기본 방법이 Spring Boot 2.5에서 재설계되었단다. 

참고한 내용들이 2.5 이전 버전 설정들이여서 정상적으로 작동한 것이다.

해결방안은 application.properties 파일에 아래 설정 값을 추가 하면 된다.

spring.jpa.defer-datasource-initialization=true

 

<참고사항>

Spring Boot 2.5 Release Notes 를 참고해 보면 아래 와 같은 내용이 나온다.
(https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes#hibernate-and-datasql)

기본적으로 data.sql 스크립트는 이제 Hibernate 초기화되기 전에 실행된다.
data.sql 사용하여 Hibernate 의해 생성된 스키마를 채우려면 spring.jpa.defer-datasource-initialization true 설정해라.
데이터베이스 초기화 기술을 혼합하는 것은 권장되지 않지만 이는 data.sql 통해 채우기 전에 하이버네이트에서 생성한 스키마를 기반으로 schema.sql 스크립트를 사용할 수도 있습니다.

Hibernate and data.sql

By default, data.sql scripts are now run before Hibernate is initialized. This aligns the behavior of basic script-based initialization with that of Flyway and Liquibase. If you want to use data.sql to populate a schema created by Hibernate, set spring.jpa.defer-datasource-initialization to true. While mixing database initialization technologies is not recommended, this will also allow you to use a schema.sql script to build upon a Hibernate-created schema before it’s populated via data.sql.

 

+ Recent posts