Spring
Lombok
print("스테코더")
2022. 11. 11. 16:13
Lombok이란? 자바 프로젝트를 진행하는데 거의 필수적으로 필요한 메소드, 생성자 등을 자동 생성해줌으로써 코드를 절약할 수 있도록 도와주는 라이브러리
설치 방법
1. 환경 설정
- Windows : Ctrl + Alt + S
- macOS : command + ,
2. 검색창에 "Annotation Processors" 입력 후, 우측 "Enable ~" 체크하고 OK 클릭
3. Shift 두 번 누르고 plugins 입력 후 엔터
4. lombok 입력 후 아래처럼 생긴 아이콘의 우측 Install 버튼 클릭 → 인텔리제이 재시작
5. 다시 Shift 두 번 누르고 plugins 입력 후 엔터
6. lombok 검색했을 때 installed 상태라면 설치 완료
lombok 사용 예시
// Getter, NoArgsConstructor 적용
@Getter
@NoArgsConstructor // 기본생성자를 대신 생성해줍니다.
@Entity // 테이블임을 나타냅니다.
public class Course extends Timestamped{
@Id // ID 값, Primary Key로 사용하겠다는 뜻입니다.
@GeneratedValue(strategy = GenerationType.AUTO) // 자동 증가 명령입니다.
private Long id;
@Column(nullable = false) // 컬럼 값이고 반드시 값이 존재해야 함을 나타냅니다.
private String title;
@Column(nullable = false)
private String tutor;
public Course(CourseRequestDto reqeustDto) {
this.title = reqeustDto.getTitle();
this.tutor = reqeustDto.getTutor();
}
public Course(String title, String tutor) {
this.title = title;
this.tutor = tutor;
}
public void update(CourseRequestDto requestDto) {
this.title = requestDto.getTitle();
this.tutor = requestDto.getTutor();
}
// RequiredArgsConstructor 적용
@RequiredArgsConstructor
@Service // 스프링에게 이 클래스는 서비스임을 명시
public class CourseService {
private final CourseRepository courseRepository;
@Transactional // SQL 쿼리가 일어나야 함을 스프링에게 알려줌
public Long update(Long id, CourseRequestDto requestDto) {
Course course1 = courseRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
);
course1.update(requestDto);
return course1.getId();
}
}