728x90
반응형
## 업데이트 기능하는 MemoService 만들기
: Service 는 업데이트 담당
1. MemoService 업데이트 기능 만들기
-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.sparta_spring.sparta_spring_week03.service;
import com.sparta_spring.sparta_spring_week03.domain.Memo;
import com.sparta_spring.sparta_spring_week03.domain.MemoRepository;
import com.sparta_spring.sparta_spring_week03.domain.MemoRequestDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor // 의존주입 생성자 자동완성
@Service // 스프링에게 서비스임을 알림
public class MemoService {
// 멤버변수
private final MemoRepository memoRepository; // 외부 의존주입
// 업데이트 메서드
@Transactional // 스프링에게 sql 연결된 것이라고 알림
public Long update(Long id, MemoRequestDto memoRequestDto){
Memo memo = memoRepository.findById(id).orElseThrow( // 리파지토리에서 찾고 없으면 예외처리
() -> new NullPointerException("찾는 메모가 없습니다.")
);
memo.update(memoRequestDto);
return id;
}
}
|
cs |
2. Memo 클래스에 update 메서드 추가로 만들어야 함
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
package com.sparta_spring.sparta_spring_week03.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@NoArgsConstructor // 빈생성자
@Getter
@Entity // 테이블과 연계됨을 스프링에게 알려줍니다.
public class Memo extends Timestamped{
// 아이디
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long id;
// 열
// 사용자 이름
@Column(nullable = false)
private String username;
// 메모 내용
@Column(nullable = false)
private String contents;
// 생성자
// 유저이름, 메모내용으로 생성자
public Memo(String username,String contents){
this.username = username;
this.contents = contents;
}
// DTO를 이용해서 생성
public Memo(MemoRequestDto requestDto){
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
}
// 업데이트 메서드
public void update(MemoRequestDto memoRequestDto){
this.username = memoRequestDto.getUsername();
this.contents = memoRequestDto.getContents();
}
}
|
cs |
반응형
'SpringBoot > 스파르타 웹개발의 봄 spring' 카테고리의 다른 글
[스파르타 웹개발의 봄 spring] 03.05 controller 만들기 (0) | 2021.07.12 |
---|---|
[스파르타 웹개발의 봄 spring] 02.09 API-GET (0) | 2021.07.12 |
[스파르타 웹개발의 봄 spring] 03.03 MemoRepository 만들기 (0) | 2021.07.12 |
[스파르타 웹개발의 봄 spring] 02.10 API-POST,PUT,DELETE (0) | 2021.07.11 |
[스파르타 웹개발의 봄 spring] 01주차 필기 (0) | 2021.07.09 |