본문 바로가기
개발 공부/Spring

[Spring] Repository / Domain / Dto 등 패키지 구조 정리

by sngynhy 2023. 12. 22.

이미지 출처: https://e-una.tistory.com/72

 

Controller

화면과 비즈니스 로직의 매개체 역할

 

Service / ServiceImpl

비즈니스 로직 담당

domain과 repository에 의존

 

Rrepository

실제로 DB에 접근하는 객체 (CRUD 수행)

service와 DB의 연결고리 역할

 

Domain

@Entity

실제 DB의 테이블과 매칭되는 객체

DB에서 가져온 데이터 저장

 

DTO

계층간 데이터 교환을 위한 객체

로직을 갖고 있지 않은 순수한 데이터 객체

단순 view를 위한 객체

 

DTO ↔ Entity(Domain) 변환은 Controller 또는 Servcie 단에서 이루어져야함

 

Domain

package com.appliance.airflowWAS.domain;

import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;
import java.time.LocalDateTime;

@Getter
@NoArgsConstructor
@ToString
@Entity
@Table(name = "user")
@DynamicInsert // insert 시 null인 필드 제외
@DynamicUpdate // update 시 null인 필드 제외
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(unique = true)
    private String userId;
    private String username;
    private String password;
    private String email;
    private int useYn;
    private int delYn;
    private String crtId;
    @CreationTimestamp
    private LocalDateTime crtDt = LocalDateTime.now();
    private String mdfId;
    @UpdateTimestamp
    private LocalDateTime mdfDt = LocalDateTime.now();

    @Builder
    public User (String userId, String username, String password, String email, int useYn, int delYn, String crtId, String mdfId) {
        this.userId = userId;
        this.userName = username;
        this.password = password;
        this.email = email;
        this.useYn = useYn;
        this.delYn = delYn;
        this.crtId = crtId;
        this.mdfId = mdfId;
    }
}

Repository

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUserId(String userId);
}

DTO

package com.appliance.airflowWAS.dto.user;

import com.appliance.airflowWAS.domain.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
    private String userId;
    private String username;
    private String email;

    public static UserDto toDto (User user) { // Entity -> Dto
        return new UserDto(user.getUserId(), user.getUsername(), user.getEmail());
    }
}

Service / ServiceImpl

package com.appliance.airflowWAS.service;

import com.appliance.airflowWAS.dto.user.UserDto;

public interface UserService {
    public UserDto findByUserId(String userId);
}
package com.appliance.airflowWAS.service;

import com.appliance.airflowWAS.domain.User;
import com.appliance.airflowWAS.dto.user.UserDto;
import com.appliance.airflowWAS.repository.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Transactional(readOnly = true)
    @Override
    public UserDto findByUserId(String userId) {
        User user = userRepository.findByUserId(userId);
        UserDto userDto = null;
        if (user != null) userDto = userDto.toDto(user);
        return userDto;
    }
}

Controller

package com.appliance.airflowWAS.controller;

import com.appliance.airflowWAS.dto.user.UserDto;
import com.appliance.airflowWAS.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private GlobalExceptionHandler globalExceptionHandler;

    @GetMapping("/{userId}")
    public ResponseEntity<?> findByUserId(@PathVariable String userId) {
        try {
            UserDto userDto = userService.findByUserId(userId);
            if (userDto != null) return new ResponseEntity<>(userDto, HttpStatus.OK);
            else return new ResponseEntity<>("존재하지 않는 계정입니다.", HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}