Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #get방식 #post방식 #http프로토콜 #클라이언트 #백엔드 #api
- 스파르타 코딩클럽 #내배캠 #최종프로젝트 #로그인 #인증인가 #jwt? #토큰인증 #액세스토큰 #리프레시토큰 #쿠키 #파싱 #서명키의 중요성 #security context holder
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #ci #ioc #의존성
- ci/cd파이프라인
- 챌린저스 #bod
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #ci #cd
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #OSI #ISO #AI #서버 #자동화 #SQL #기본문법 #데이터베이스 #DBMS #Oracle #MongoDB #아키텍쳐 #DB
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #대용량트래픽 #처리방법 #캐싱 #코드최적화 #db최적화 #트래픽 #로드밸런서
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #aop #관점지향프로그래밍 #유지보수
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스 #웹개발
- java5기
- 쓰레드 #쓰레드풀 #프로세스
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #최종프로젝트 #aws s3 #프로필 이미지 수정 #자동삭제
- 보안 #이슈
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #딥러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스 #DBMS #Oracle #MongoDB #아키텍쳐 #DB
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #AI #서버 #자동화 #SQL #KDT #기본문법 #데이터베이스 #Computer #Science #CPU #메모리
- 비트 #바이트 #이진수
- 공간복잡도 #공간자원 #캐시메모리 #SRAM #DRAM #시간복잡도
- 프로세스 #CPU #시공유 #커널
- 스파르타 코딩클럽 #내배캠 #최종프로젝트 #4개월삭제 #국비지원 #자바
- 인가 #
- 스프링 #백엔드 #자바
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #소셜로그인 #네이버 #기능구현 #vue.js #spring boot #네이버로그인 #연동하기
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #springmvc패턴 #model #view #controller
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스
- 스파르타 코딩클럽 #인메모리db #h2 #연동이슈 #문제해결 #방법 #spring security #header #
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #딥러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #tdd #테스트 주도개발 #테스트코드 #유닛테스트
- spring security #jwt 토큰 #json web token #token #직렬화 #인증
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #트랜잭션전파 #transaction
Archives
- Today
- Total
요리사에서 IT개발자로
스파르타 부트캠프 스프링 부트 U(update)D(delete) 다락방 본문
User Entity
@Table(name = "USER_TABLE")
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column
private String name;
@Column
private Long age;
public User(String name, Long age) {
this.name = name;
this.age = age;
}
User를 생성할 dto생성
@Getter
public class UserCreateDto {
private String name;
private Long age;
}
Controller
@Controller
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/users")
public ResponseEntity save(@RequestBody UserCreateDto dto) {
userService.create(dto);
return new ResponseEntity(HttpStatus.OK);
}
Serivce
@Transactional
public void create(UserCreateDto dto) {
User user = new User(dto.getName(), dto.getAge());
userRepository.save(user);
}
UserCreateDto 의 Name과 age를 가져와서 user객체에 전달하고
userRepository의 save메소드를 사용하여
user를 저장한다
Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
생성되는것을 확인할 수 있다.
Update
dto
@Getter
public class UserUpdateDto {
private Long id;
private String name;
}
entity에 update 추가
@Entity
@Table(name = "USER_TABLE")
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column
private String name;
@Column
private Long age;
public User(String name, Long age) {
this.name = name;
this.age = age;
}
public void update (String name){
this.name = name;
}
}
controller
@PutMapping("/users/{id}")
public ResponseEntity update(@PathVariable Long id, @RequestBody UserUpdateDto dto) {
userService.update(id, dto);
return new ResponseEntity(HttpStatus.OK);
}
service
@Transactional
public void update(Long id, UserUpdateDto dto) {
if(!Objects.equals(id, dto.getId())){
throw new RuntimeException("수정하려는 사용자가 아닙니다");
}
User user = userRepository.findById(id).orElseThrow(() ->
new RuntimeException("사용자가 존재하지 않습니다"));
user.update(dto.getName());
// userRepository.save(user);
}
Objects의 equals 메소드를 사용해서
id와 UserUpdateDto안의 id를 가져와서 확인한다.
일치하지않으면 RunTimeException 하고
userRepository에 일치하는 id를 가져와서 user객체에 전달하고
User Entity에 update를 가져와서 dto.getName() 을 하여
해당 id의 정보를 변환
@Transactional 로 선언했기에 userRepository에 save를 하지않아도
DB에 데이터가 바뀌었기에 저장되는것을 확인할 수 있다.
Delete
확인할 id dto 생성
@Getter
public class UserDeleteDto {
private Long id;
}
controller
@DeleteMapping("/users/{id}")
public void delete(@PathVariable Long id, @RequestBody UserDeleteDto deleteDto) {
userService.delete(id, deleteDto);
}
service
public void delete(Long id, UserDeleteDto deleteDto) {
if(!Objects.equals(id, deleteDto.getId())){
throw new RuntimeException("수정하려는 사용자가 아닙니다");
}
userRepository.deleteById(id);
}
@PathVariable
url에 id를 입력한 것과 deleteDto의 id가 일치하지않으면
수정하려는 사용자가 아니라는 RuntimeException 처리를 하고
맞다면
userRepository에 deleteById 메소드를 사용하여
삭제를 한다.(Hard Delete)
@Transactional 어노테이션을 설정하지 않아도
userRepository의 저장된 id를 찾아와 삭제를 하는것이기에
삭제되는것을 확인할 수 있다.
Soft Delete
데이터를 완전삭제하지않고 삭제처리한 흔적을 남기고
DB에 저장하여 데이터를 보관한다.
복원해야 될 경우가 생길 수 있기에
Hard Delete
DB안의 해당 데이터를 완전삭제처리 한다.
굳이 저장할 필요가 없이 완전삭제처리 해도되는 경우에 사용한다.
https://velog.io/@yhlee9753/soft-delete-%EC%99%80-hard-delete-%EB%B9%84%EA%B5%90
반응형
'Spring' 카테고리의 다른 글
Spring Boot JUnit 과 TDD, 단위테스트와 통합테스트 (1) | 2024.06.15 |
---|---|
스파르타 부트캠프 REST API 요청과 응답 (다락방) (0) | 2024.06.14 |
스파르타 부트캠프 스프링 부트 프로젝트 생성 및 CR (다락방) (1) | 2024.06.12 |
스프링 시큐리티 내부 구조 Security Filter Chain 등록, 여러개 등록, 특정 요청 허가 (1) | 2024.06.11 |
Spring Security 내부 구조 DelegatingFilterProxy와 FilterChainProxy (0) | 2024.06.11 |