src > main > resources > application.properties에 아래 내용을 넣어주면
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MYSQL;
http://localhost:8080/h2-console에서 db 확인 할 수 있다.
<시간>
@EnableJpaAuditing
Application에 넣어줘야 함.
<1개 조회>
@GetMapping("/api/boards/{id}")
public Optional<Board> findById(@PathVariable Long id){
return boardRepository.findById(id);
}
<비밀번호 확인>
-------BoardController
@PostMapping("/api/boards/{id}")
public boolean checkPass(@PathVariable Long id, @RequestBody BoardRequestDto requestDto) {
boolean result = boardService.checkPass(id,requestDto.getPassword());
return result;
}
-----BoardService
public boolean checkPass(Long id, String password) {
Board board = boardRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
if(board.getPassword().equals(password)){
return true;
}else{
return false;
}
}
<JSON 일부 필드만 나타내기>
@JsonIgnore
제이슨 결과창에서 숨김.(DB저장은 ㅇㅇ)
아래 블로그는
[@JsonIgnore, @JsonIgnoreProperties, @JsonIgnoreType차이점]
@JsonIgnore 어노테이션은 클래스의 속성(필드, 멤버변수) 수준에서 사용되고
@JsonIgnoreProperties 어노테이션은 클래스 수준(클래스 선언 바로 위에)에 사용됩니다.
@JsonIgnoreType 어노테이션은 클래스 수준에서 사용되며 전체 클래스를 무시합니다.
https://velog.io/@hth9876/JsonIgnorePropertiesignoreUnknown-trueㅇ
@JsonIgnore, @JsonIgnoreProperties, @JsonIgnoreType차이점
json 데이터를 받아와서 객체로 맵핑할 때 클래스에 선언되지 않은 프로퍼티가 json에 있으면 오류 발생 (json 구성 = 클래스 구성)이럴 때 예외 발생시키지 말고 무시출처: https://darksilber.tistory.com/28
velog.io
<1차 완성>
------BoardController
package com.sparta.w1homework.controller;
import com.sparta.w1homework.dto.BoardRequestDto;
import com.sparta.w1homework.entity.Board;
import com.sparta.w1homework.repository.BoardRepository;
import com.sparta.w1homework.service.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RequiredArgsConstructor
@RestController
public class BoardController {
private final BoardRepository boardRepository;
private final BoardService boardService;
@PostMapping("/api/boards")
public Board createBoard(@RequestBody BoardRequestDto requestDto) {
Board board = new Board(requestDto);
return boardRepository.save(board);
}
@GetMapping("/api/boards")
public List<Board> getBoard() {
return boardRepository.findAllByOrderByModifiedAtDesc();
}
@GetMapping("/api/boards/{id}")
public Optional<Board> findById(@PathVariable Long id){
return boardRepository.findById(id);
}
@DeleteMapping("/api/boards/{id}")
public String deleteBoard(@PathVariable Long id) {
boardRepository.deleteById(id);
return "삭제완료";
}
@PutMapping("/api/boards/{id}")
public String updateBoard(@PathVariable Long id, @RequestBody BoardRequestDto requestDto) {
boardService.update(id, requestDto);
return "수정완료";
}
@PostMapping("/api/boards/{id}")
public boolean checkPass(@PathVariable Long id, @RequestBody BoardRequestDto requestDto) {
boolean result = boardService.checkPass(id,requestDto.getPassword());
return result;
}
}
----BoardRequestDto
package com.sparta.w1homework.dto;
import lombok.Getter;
@Getter
public class BoardRequestDto {
private String title;
private String username;
private String contents;
private String password;
}
-----Board
package com.sparta.w1homework.entity;
import com.sparta.w1homework.dto.BoardRequestDto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@NoArgsConstructor // 기본생성자를 만듭니다.
@Getter
@Entity // 테이블과 연계됨을 스프링에게 알려줍니다.
public class Board extends Timestamped { // 생성,수정 시간을 자동으로 만들어줍니다.
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long id;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String contents;
@Column(nullable = false)
private String password;
public Board(String title, String username, String contents, String password) {
this.title = title;
this.username = username;
this.contents = contents;
this.password = password;
}
public Board(BoardRequestDto requestDto) {
this.title = requestDto.getTitle();
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
this.password = requestDto.getPassword();
}
public void update(BoardRequestDto requestDto) {
this.title = requestDto.getTitle();
this.username = requestDto.getUsername();
this.contents = requestDto.getContents();
this.password = requestDto.getPassword();
}
}
-----Timestamped
package com.sparta.w1homework.entity;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@MappedSuperclass // Entity가 자동으로 컬럼으로 인식합니다.
@EntityListeners(AuditingEntityListener.class) // 생성/변경 시간을 자동으로 업데이트합니다.
public class Timestamped {
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime modifiedAt;
}
-----BoardRepository
package com.sparta.w1homework.repository;
import com.sparta.w1homework.entity.Board;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BoardRepository extends JpaRepository<Board, Long> {
List<Board> findAllByOrderByModifiedAtDesc();
}
-----BoardService
package com.sparta.w1homework.service;
import com.sparta.w1homework.dto.BoardRequestDto;
import com.sparta.w1homework.entity.Board;
import com.sparta.w1homework.repository.BoardRepository;
import lombok.RequiredArgsConstructor;
import org.hibernate.type.TrueFalseType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
@Service
public class BoardService {
private final BoardRepository boardRepository;
@Transactional
public Long update(Long id, BoardRequestDto requestDto) {
Board board = boardRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
board.update(requestDto);
return board.getId();
}
public boolean checkPass(Long id, String password) {
Board board = boardRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
if(board.getPassword().equals(password)){
return true;
}else{
return false;
}
}
}
----W1homeworkApplication
package com.sparta.w1homework.service;
import com.sparta.w1homework.dto.BoardRequestDto;
import com.sparta.w1homework.entity.Board;
import com.sparta.w1homework.repository.BoardRepository;
import lombok.RequiredArgsConstructor;
import org.hibernate.type.TrueFalseType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
@Service
public class BoardService {
private final BoardRepository boardRepository;
@Transactional
public Long update(Long id, BoardRequestDto requestDto) {
Board board = boardRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
board.update(requestDto);
return board.getId();
}
public boolean checkPass(Long id, String password) {
Board board = boardRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("아이디가 존재하지 않습니다.")
);
if(board.getPassword().equals(password)){
return true;
}else{
return false;
}
}
}
'항해99' 카테고리의 다른 글
3주차 러프 메모 기록 (0) | 2022.10.07 |
---|---|
3주차 키워드 정리 (0) | 2022.10.06 |
항해 2주차 WIL (객체지향 프로그래밍이란? or JVM) (0) | 2022.10.02 |
자바 버전확인 (0) | 2022.10.02 |
Static (0) | 2022.10.01 |