프로젝트 요구사항 명세에 의해 PostgreSQL과 QueryDSL을 사용하게 되었기에 간단히 알아보았다.
작업환경: Mac
터미널에서 PostgreSQL 설치
brew install postgresql
+postgres --version으로 버전 확인

서버 시작
brew services start postgresqlpg_ctl -D /usr/local/var/postgres startbrew info postgresql로 확인PostgreSQL 접속
psql postgres
계정 확인
\du

계정에 비밀번호 설정
\password {사용자명}

데이터베이스 목록 확인
\l

데이터베이스 생성
CREATE DATABASE {데이터베이스명}

의존성 추가
'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.postgresql:postgresql'dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.postgresql:postgresql'
// 추가적으로 필요에 따라 웹 의존성도 추가 가능
implementation 'org.springframework.boot:spring-boot-starter-web'
}<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency><dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- 추가적으로 필요에 따라 웹 의존성도 추가 가능 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>application.properties
# 데이터베이스 연결 정보
spring.datasource.url=jdbc:postgresql://localhost:5432/{데이터베이스명}
spring.datasource.username={사용자명}
spring.datasource.password={비밀번호}
spring.datasource.driver-class-name=org.postgresql.Driver
application.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/{데이터베이스명}
username: {사용자명}
password: {비밀번호}
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
database-platform: org.hibernate.dialect.PostgreSQLDialect
Database -> new -> Data Source -> PostgreSQL

User, Password, Database 지정 후 test 및 connect

+PostgreSQL 서버 종료
brew services stop postgresql
dependencies {
implementation 'com.querydsl:querydsl-jpa'
implementation 'com.querydsl:querydsl-apt'
annotationProcessor 'com.querydsl:querydsl-apt'
annotationProcessor 'javax.persistence:javax.persistence-api'
}
plugins {
id 'com.ewerk.gradle.plugins.querydsl' version '1.0.10'
}
querydsl {
jpa = true
querydslSourcesDir = 'src/main/generated'
}
sourceSets {
main {
java {
srcDir 'src/main/generated'
}
}
}
설정 후 빌드하면 build/generated 디렉토리에 Q 클래스들이 자동으로 생성됨
+Q 클래스: 엔티티 클래스의 필드에 접근할 수 있는 타입 안전한 메서드를 제공
@Configuration
public class QueryDslConfig {
@PersistenceContext
private EntityManager entityManager;
@Bean
public JPAQueryFactory jpaQueryFactory() {
return new JPAQueryFactory(entityManager);
}
}
@Service
public class UserService {
private final JPAQueryFactory queryFactory;
@Autowired
public UserService(JPAQueryFactory queryFactory) {
this.queryFactory = queryFactory;
}
public List<User> getUsersBySomeCriteria(String criteria) {
QUser user = QUser.user;
return queryFactory.selectFrom(user)
.where(user.name.eq(criteria))
.fetch();
}
}