[TIL] 2021.11.05

SeonMan Kim·2021년 11월 7일
1

TIL / WIL

목록 보기
7/7

상속 연습

class Person {
    private String name;
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Tutor extends Person {
	private String address;
	// Person 클래스를 상속했기 때문에,
	// name 멤버변수와 getName() 메소드를 가지고 있습니다.
}
public class Prac {
    public static void main(String[] args) {
        Tutor tutor = new Tutor();
        tutor.setName("홍길동");
        System.out.println(tutor.getName());
    }
}
  • 만약 이런 상태일 때 생성일자와 수정일자를 추가하고 싶다면 아래와 같이 상속을 받고 수정한다.
@MappedSuperclass // 상속했을 때, 컬럼으로 인식하게 합니다.
@EntityListeners(AuditingEntityListener.class) // 생성/수정 시간을 자동으로 반영하도록 설정
public class Timestamped {

    @CreatedDate // 생성일자임을 나타냅니다.
    private LocalDateTime createdAt;

    @LastModifiedDate // 마지막 수정일자임을 나타냅니다.
    private LocalDateTime modifiedAt;
}

// 상속으로 받아 수정
class Lecture extends Timestamped {
	... (생략)
}

@EnableJpaAuditing			// 추가
@SpringBootApplication
public class Item01Application {
	... (생략)
}

MVC

Service

비즈니스로직을 설정하는 곳으로 @Service 에노테이션 으로 서비스와 관련된 클래스라고 스프링부트에게 알려준다.


@Entity // 테이블임을 나타냅니다.
public class Lecture {
	... (중간생략)
    public Lecture(String title, String tutor) {
        this.title = title;
        this.tutor = tutor;
    }
}

@Service // 스프링에게 이 클래스는 서비스임을 명시
public class LectureService {

    // final: 서비스에게 꼭 필요한 녀석임을 명시
    private final LectureRepository lectureRepository;

    // 생성자를 통해, Service 클래스를 만들 때 꼭 Repository를 넣어주도록
    // 스프링에게 알려줌
    public LectureService(LectureRepository lectureRepository) {
        this.lectureRepository = lectureRepository;
    }

    @Transactional // SQL 쿼리가 일어나야 함을 스프링에게 알려줌
    public Long update(Long id, Lecture lecture) {
        Lecture lecture1 = lectureRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
        );
        lecture1.update(lecture);
        return lecture1.getId();
    }
}

@Bean
public CommandLineRunner demo(CourseRepository lectureRepository, LectureService lectureService) {
    return (args) -> {
        Lecture new_lecture = new Lecture("웹개발의 봄, Spring", "임민영");
        lectureService.update(1L, new_lecture);
    };
}

DTO

서로 다른 프로세스가 통신하려면 부하가 많이 발생한다. 그렇기 때문에 데이터를 교환할 때 전달하고 받는 양식을 하나의 데이터로 설정한 후 서로 통신한다. 이 때 사용되는 데이터가 DTO 이다.

@NoArgsConstructor
@Getter
public class LectureRequestDto {
    private String title;
    private String tutor;

    public LectureRequestDto(String title, String tutor) {
        this.title = title;
        this.tutor = tutor;
    }
}

Lombok

보일러플레이트코드인 생성자와 Getter/Setter를 작성할 필요없이 자동으로 추가해준다.

@RequiredArgsConstructor
@Service
public class LectureService {
    private final LectureRepository lectureRepository;

    @Transactional
    public Long update(Long id, LectureRequestDto requestDto) {
        Lecture lecture1 = lectureRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
        );
        lecture1.update(requestDto);
        return lecture1.getId();
    }
}
@Getter
@NoArgsConstructor
@Entity
public class Course extends Timestamped {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String tutor;

    public Course(String title, String tutor) {
        this.title = title;
        this.tutor = tutor;
    }

    public void update(LectureRequestDto requestDto) {
        this.title = requestDto.getTitle();
        this.tutor = requestDto.getTutor();
    }
}

@NoArgsConstructor : 기본 생성자 생성
@RequiredArgsConstructor : Final이나 @NotNull 어노테이션이 설정된 멤버변수 생성자 사용
@AllArgsConstructor : 모든 멤버변수가 설정된 생성자 사용

참고

데이터 전송 객체 - 위키백과, 우리 모두의 백과사전
IT 삽질 :: [Lombok] @NoArgsConstructor , @AllArgsConstructor , @RequiredArgsConstructor

profile
안녕하세요

0개의 댓글