6.4. Repository 계층 작성 규칙
6.4.1. Repository 구조
Repository 클래스는 DSLContext를 주입받아 사용합니다.
java
@Repository
@RequiredArgsConstructor
public class UserRepository {
private final DSLContext dsl;
}6.4.2. 조회 (SELECT)
단건 조회:
java
public Optional<UsersRecord> findById(Long id) {
return dsl.selectFrom(USERS)
.where(USERS.ID.eq(id))
.fetchOptional();
}
public Optional<UsersRecord> findByEmail(String email) {
return dsl.selectFrom(USERS)
.where(USERS.EMAIL.eq(email))
.fetchOptional();
}목록 조회:
java
public List<UsersRecord> findAll() {
return dsl.selectFrom(USERS)
.orderBy(USERS.CREATED_AT.desc())
.fetch();
}
public List<UsersRecord> findByIsActive(boolean isActive) {
return dsl.selectFrom(USERS)
.where(USERS.IS_ACTIVE.eq(isActive))
.orderBy(USERS.NAME.asc())
.fetch();
}6.4.3. 생성 (INSERT)
java
public UsersRecord insert(String name, String email) {
return dsl.insertInto(USERS)
.set(USERS.NAME, name)
.set(USERS.EMAIL, email)
.returning()
.fetchOne();
}6.4.4. 수정 (UPDATE)
java
public int update(Long id, String name) {
return dsl.update(USERS)
.set(USERS.NAME, name)
.set(USERS.UPDATED_AT, OffsetDateTime.now())
.where(USERS.ID.eq(id))
.execute();
}6.4.5. 삭제 (DELETE)
java
public int deleteById(Long id) {
return dsl.deleteFrom(USERS)
.where(USERS.ID.eq(id))
.execute();
}6.4.6. 조건 검색 (동적 쿼리)
Condition을 조합하여 동적 쿼리를 작성합니다.
java
public List<UsersRecord> search(String name, String email, Boolean isActive) {
Condition condition = DSL.noCondition();
if (name != null) {
condition = condition.and(USERS.NAME.containsIgnoreCase(name));
}
if (email != null) {
condition = condition.and(USERS.EMAIL.eq(email));
}
if (isActive != null) {
condition = condition.and(USERS.IS_ACTIVE.eq(isActive));
}
return dsl.selectFrom(USERS)
.where(condition)
.orderBy(USERS.CREATED_AT.desc())
.fetch();
}6.4.7. 조인 쿼리
java
public List<Record> findOrdersWithUserName(Long userId) {
return dsl.select(
ORDERS.ID,
ORDERS.PRODUCT_NAME,
ORDERS.AMOUNT,
USERS.NAME.as("user_name"))
.from(ORDERS)
.join(USERS).on(ORDERS.USER_ID.eq(USERS.ID))
.where(ORDERS.USER_ID.eq(userId))
.orderBy(ORDERS.CREATED_AT.desc())
.fetch();
}6.4.8. 페이지네이션
java
public List<UsersRecord> findPage(int page, int size) {
return dsl.selectFrom(USERS)
.orderBy(USERS.CREATED_AT.desc())
.limit(size)
.offset(page * size)
.fetch();
}
public long count() {
return dsl.fetchCount(USERS);
}서비스 레이어에서 페이지 응답을 조립합니다:
java
public PageResponse<UserResponse> findUsers(int page, int size) {
List<UsersRecord> records = userRepository.findPage(page, size);
long totalElements = userRepository.count();
List<UserResponse> content = records.stream()
.map(UserResponse::from)
.toList();
return new PageResponse<>(content, page, size, totalElements);
}