본문으로 건너뛰기

첫 번째 프로젝트 만들기

이 튜토리얼에서는 ElastiCORE로 단 5분 만에 완전한 사용자 관리 시스템을 구축합니다.

완성 결과물

이 튜토리얼을 완료하면 다음을 갖추게 됩니다:

  • 전체 CRUD API를 갖춘 User 엔티티
  • 이름과 이메일로 검색 가능한 REST API
  • 자동 페이지네이션 및 정렬 지원
  • 웹 콘솔 접근 가능한 H2 데이터베이스

사전 요구 사항

  • Java 17+ 설치
  • IntelliJ IDEA 또는 VS Code (어노테이션 프로세싱 지원 필수)
  • ElastiCORE 프로젝트 템플릿 준비

단계별 가이드

Step 1: 기본 프로젝트 구조 생성

Spring Boot 프로젝트에 ElastiCORE 의존성을 추가합니다 (Spring Initializr 또는 기존 프로젝트 사용).

build.gradle
dependencies {
// ElastiCORE 핵심 의존성
implementation 'io.elasticore:elasticore-base:1.8.250924-SNAPSHOT'
implementation 'io.elasticore.springboot3:elasticore-springboot3:1.8.250924-SNAPSHOT'

// Spring Boot 기본 스택
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'

// H2 데이터베이스 (개발용)
runtimeOnly 'com.h2database:h2'

// Lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}

// ElastiCORE 코드 생성 태스크
tasks.register('elcore', JavaExec) {
classpath = sourceSets.main.runtimeClasspath
mainClass = 'io.elasticore.base.extract.ModelExtractor'
args "$projectDir/src/main/java"
}

Step 2: 메인 애플리케이션 클래스 설정

Application.java
package com.example.myproject;

import io.elasticore.springboot3.EnableElastiCore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableElastiCore // ElastiCORE 활성화
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Step 3: 환경 설정 파일 생성

src/main/resources/blueprint/env.yml
elasticore:
enable: true
config:
domainName: user
framework: springboot
mode: jpa
j2ee: jakarta

# 테스트 코드 자동 생성
testCode:
enabled: true
framework: junit5
mockFramework: mockito

namespace:
entity: com.example.myproject.domain.entity
dto: com.example.myproject.domain.dto
repository: com.example.myproject.domain.repository
service: com.example.myproject.domain.service
control: com.example.myproject.web.controller

Step 4: 도메인 모델 정의

src/main/resources/blueprint/models.yml
entity:
User:
meta: entity @expose(20) @audited
fields:
id: string(36)! @id @genid
username: string(50)! @search(like) @unique
email: string(100)! @search(eq) @unique
fullName: string(100) @search(like)
isActive: boolean @default(true) @search(eq)
createdDate: datetime @jpa:org.springframework.data.annotation.CreatedDate
lastModifiedDate: datetime @jpa:org.springframework.data.annotation.LastModifiedDate

UserProfile:
meta: entity @service(10) # Service만 생성, Controller 없음
fields:
id: string(36)! @id @genid
user: User @OneToOne @cascade(ALL) @fetchjoin
bio: text @search(like)
avatarUrl: string(500)
website: string(300)
location: string(100) @search(like)
createdDate: datetime @jpa:org.springframework.data.annotation.CreatedDate

Step 5: Spring Boot 설정

application.yml
spring:
datasource:
url: jdbc:h2:mem:devdb;DB_CLOSE_DELAY=-1
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
h2:
console:
enabled: true
path: /h2-console

logging:
level:
io.elasticore: DEBUG
org.springframework.web: INFO

Step 6: 코드 생성 및 빌드

# 1. ElastiCORE 코드 생성
./gradlew elcore

# 2. 프로젝트 컴파일
./gradlew compileJava

# 3. 애플리케이션 실행
./gradlew bootRun

정상 실행 시 다음과 같은 출력을 확인할 수 있습니다:

ElastiCORE Code Generation completed:
- Generated 2 entities: User, UserProfile
- Generated 4 DTOs: UserDTO, UserSearchDTO, UserProfileDTO, UserProfileSearchDTO
- Generated 2 repositories with Specification support
- Generated 2 services with CRUD operations
- Generated 1 controller with REST API
- Generated 6 test classes

Started Application in 2.847 seconds

자동 생성된 코드 구조

ElastiCORE가 완전한 Spring Boot 스택을 생성합니다:

src/main/java/com/example/myproject/
├── domain/
│ ├── entity/
│ │ ├── User.java # JPA 엔티티 (전체 어노테이션 포함)
│ │ └── UserProfile.java # 1:1 관계 엔티티
│ ├── dto/
│ │ ├── UserDTO.java # 데이터 전송 객체
│ │ ├── UserSearchDTO.java # 동적 검색 DTO
│ │ ├── UserProfileDTO.java
│ │ └── UserProfileSearchDTO.java
│ ├── repository/
│ │ ├── UserRepository.java # JpaRepository + JpaSpecificationExecutor
│ │ └── UserProfileRepository.java
│ └── service/
│ ├── UserService.java # 완전한 CRUD + 검색 로직
│ └── UserProfileService.java
└── web/
└── controller/
└── UserController.java # OpenAPI 문서화된 REST API

API 테스트

1. Swagger UI 접속

브라우저에서 http://localhost:8080/swagger-ui.html 을 열면 자동 생성된 API 문서를 확인할 수 있습니다.

2. 자동 생성된 REST API 엔드포인트

User 관리 API:
GET /api/users # 사용자 목록 조회 (페이지네이션)
GET /api/users/{id} # 특정 사용자 조회
POST /api/users # 새 사용자 생성
PUT /api/users/{id} # 사용자 수정
DELETE /api/users/{id} # 사용자 삭제
GET /api/users/search # 동적 검색 API

UserProfile 관리 API:
- Service 레이어만 생성 (REST API 없음)
- 의존성 주입을 통해 UserProfileService 사용

3. 사용자 생성

curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{
"username": "johndoe",
"email": "john.doe@example.com",
"fullName": "John Doe",
"isActive": true
}'

4. 동적 검색

자동 생성된 검색 API는 매우 강력합니다:

# 사용자명 부분 검색 (LIKE)
curl "http://localhost:8080/api/users/search?username=john"

# 이메일 정확한 검색 (EQUALS)
curl "http://localhost:8080/api/users/search?email=john.doe@example.com"

# 활성 사용자만 조회
curl "http://localhost:8080/api/users/search?isActive=true"

# 복합 검색 조건
curl "http://localhost:8080/api/users/search?username=john&isActive=true"

# 페이지네이션 및 정렬
curl "http://localhost:8080/api/users/search?username=john&pageNumber=0&pageSize=10&sortCode=createdDate,desc"

5. H2 데이터베이스 콘솔

  1. http://localhost:8080/h2-console 에 접속
  2. 연결 정보:
    • JDBC URL: jdbc:h2:mem:devdb
    • Username: sa
    • Password: (빈 값)

커스터마이징 & 확장

1. 커스텀 비즈니스 로직 추가

생성된 서비스를 상속하여 자체 로직을 추가합니다:

CustomUserService.java
@Service
@Primary // 기본 UserService 대신 이 클래스를 사용
public class CustomUserService extends UserService {

@Autowired
private UserProfileService userProfileService;

public UserDTO createUserWithProfile(UserDTO userDTO, UserProfileDTO profileDTO) {
UserDTO createdUser = super.create(userDTO);
profileDTO.setUserId(createdUser.getId());
userProfileService.create(profileDTO);
return createdUser;
}
}

2. 검색 조건 확장

모델을 수정하고 재생성하여 검색 조건을 추가합니다:

models.yml - 검색 조건 추가
entity:
User:
fields:
createdDate: datetime @jpa:org.springframework.data.annotation.CreatedDate @search(between)
# 날짜 범위 검색 자동 생성: createdDateFrom, createdDateTo

다음 단계

첫 번째 프로젝트를 성공적으로 완료했습니다! 계속 학습하세요:

문제 해결

1. 코드 생성이 실행되지 않는 경우

# 해결 방법:
# 1. 메인 클래스에 @EnableElastiCore 어노테이션이 있는지 확인
# 2. 블루프린트 디렉토리 경로 확인
# 3. 실행: ./gradlew clean elcore

2. 컴파일 에러

# 에러: cannot find symbol: class UserService
# 해결 방법: 코드를 먼저 생성한 후 컴파일
./gradlew elcore
./gradlew compileJava

3. API 호출 시 404 에러

# 원인: Controller가 생성되지 않음
# 해결 방법: @expose 어노테이션 확인
entity:
User:
meta: entity @expose(20) # Controller 생성에 이 어노테이션이 필수

개발 팁
  1. 점진적 개발: 작은 모델로 시작하여 점차 확장하세요
  2. 코드 리뷰: 생성된 코드를 읽어보며 ElastiCORE 패턴을 학습하세요
  3. 테스트 우선: 자동 생성된 테스트 코드를 먼저 실행하세요
  4. 문서화: Swagger UI를 활용하여 자동 API 문서화를 확인하세요