Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'



compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
Expand Down
40 changes: 23 additions & 17 deletions src/main/java/com/likelion/session/controller/BoardController.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@

import java.util.List;

@RestController
@RequestMapping("/boards")
@RequiredArgsConstructor
@RestController // 외부 요청을 받아 데이터 반환하는 컨트롤러
@RequestMapping("/boards") // 클라이언트가 boards라는 주소로 접근하면 클래스로 연결해줌
@RequiredArgsConstructor // 객체를 이용할 때 필요한 생성자 자동으로 생성
public class BoardController {

private final ;
private final BoardService boardService;

/*
게시글 생성
Expand All @@ -32,58 +32,64 @@ public class BoardController {
-> 결과 반환
-> JSON 응답
*/
@Operation(
@Operation // 메서드 기능에 대한 설명을 적는 곳
(
summary = "게시글 생성",
description = "새로운 게시글을 생성합니다."
)
@
@PostMapping // 데이터를 새로 create 할 때 사용, 클라이언트가 post 요청하면 실행됨
public ResponseEntity<BoardResponse> create(@RequestBody BoardCreateRequest request) {
BoardResponse response = boardService.create(request);
return ResponseEntity.ok(response);
return ResponseEntity.ok(response); //@RequestBody: 클라이언트가 보내는 데이터를 자바 객체로 변환해서 받아줌
}

// 게시글 전체 조회
@Operation(
@Operation //메서드 기능에 대한 설명을 적는 곳
(
summary = "게시글 전체 조회",
description = "등록된 모든 게시글을 조회합니다."
)
@
@GetMapping //데이터 조회할 때 사용됨
public ResponseEntity<List<BoardResponse>> findAll() {
List<BoardResponse> response = boardService.findAll();
return ResponseEntity.ok(response);
}

// 게시글 단건 조회
@Operation(
@Operation //메서드 기능에 대한 설명을 적는 곳
(
summary = "게시글 단건 조회",
description = "id로 특정 게시글을 조회합니다."
)
@GetMapping("/{id}")
@GetMapping("/{id}") //데이터 조회할 때 사용됨
public ResponseEntity<BoardResponse> findById(@PathVariable Long id) {
BoardResponse response = boardService.findById(id);
return ResponseEntity.ok(response);
return ResponseEntity.ok(response); // @PathVariable: URL주소에 포함된 변수 값을 읽어옴
}

// 게시글 수정
@Operation(
@Operation //메서드 기능에 대한 설명을 적는 곳
(
summary = "게시글 수정",
description = "id로 특정 게시글의 제목과 내용을 수정합니다."
)
@("/{id}")
@PutMapping("/{id}") // 데이터를 update할 때 사용
public ResponseEntity<BoardResponse> update(@PathVariable Long id,
@RequestBody BoardUpdateRequest request) {
BoardResponse response = boardService.update(id, request);
return ResponseEntity.ok(response);
return ResponseEntity.ok(response); //@RequestBody: 클라이언트가 보내는 데이터를 자바 객체로 변환해서 받아줌
}

// 게시글 삭제
@Operation(
@Operation //메서드 기능에 대한 설명을 적는 곳
(
summary = "게시글 삭제",
description = "id로 특정 게시글을 삭제합니다."
)
@("/{id}")
@DeleteMapping("/{id}") //데이터 delete 할 때 사용
public ResponseEntity<Void> delete(@PathVariable Long id) {
boardService.delete(id);
//@PathVariable: URL주소에 포함된 변수 값을 읽어옴
return ResponseEntity.noContent().build();
}
}
36 changes: 18 additions & 18 deletions src/main/java/com/likelion/session/domain/Board.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,34 @@

@Getter // getter 메서드 자동 생성
@Entity // 해당 클래스 DB 테이블로 인식하고 관리
@Table(name = "boards")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Table(name = "boards") //DB에 생성될 테이블 이름 지정
@NoArgsConstructor(access = AccessLevel.PROTECTED) //파라미터가 없는 기본 생성자 만드는데, 보안상 외부 패키지에서 Board()못하게 막아줌
@AllArgsConstructor //모든 필드를 다 넣어서 객체를 만드는 생성자 자동 생성
public class Board {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ;
@Id //이 필드가 테이블의 PK임을 나타냄
@GeneratedValue(strategy = GenerationType.IDENTITY) //ID값을 DB가 알아서 순서대로 넣어주도록 설정
private Long id;

// 게시글 제목
@Column(nullable = false, length = 100)
private String ;
@Column(nullable = false, length = 100) //변수를 DB 칼럼과 연결
private String title;

// 게시글 내용
@Column(nullable = false, columnDefinition = "TEXT")
private String ;
@Column(nullable = false, columnDefinition = "TEXT") //변수를 DB 칼럼과 연결
private String content;

// 작성자
@Column(nullable = false, length = 30)
private String ;
@Column(nullable = false, length = 30) //변수를 DB 칼럼과 연결
private String writer;

// 생성 시간
@Column(nullable = false)
private LocalDateTime ;
@Column(nullable = false) //변수를 DB 칼럼과 연결
private LocalDateTime createdAt;

// 수정 시간
@Column(nullable = false)
private LocalDateTime ;
@Column(nullable = false) //변수를 DB 칼럼과 연결
private LocalDateTime updatedAt;


public Board(String title, String content, String writer) {
Expand All @@ -46,13 +46,13 @@ public Board(String title, String content, String writer) {
this.writer = writer;
}

@PrePersist
@PrePersist //데이터를DB에 처음 저장하기 전에 이 메서드 실행
public void prePersist() {
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
}

@PreUpdate
@PreUpdate //데이터 Update 전에 이 메서드 실행 수정될때마다 updateAt만 최신 시간으로 갱신
public void preUpdate() {
this.updatedAt = LocalDateTime.now();
}
Expand Down
14 changes: 7 additions & 7 deletions src/main/java/com/likelion/session/dto/BoardCreateRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Getter //클래스 안의 변수 값을 외부에서 꺼내올 수 있게 메서드 자동 생성
@Setter //클래스 내부의 변수값을 변경할 수 있는 메서드 자동 생성
@NoArgsConstructor //파라미터가 하나도 없는 빈 생성자 만들어줌
@AllArgsConstructor //모든 변수를 파라미터로 받는 생성자 자동 생성
public class BoardCreateRequest {
// 넘겨주고 싶은 정보: 제목(title), 내용(content), 작성자(writer)
private String ;
private String ;
private String ;
private String title;
private String content;
private String writer;
}
6 changes: 3 additions & 3 deletions src/main/java/com/likelion/session/dto/BoardResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@

import java.time.LocalDateTime;

@Getter
@AllArgsConstructor
@Builder
@Getter //클래스 안의 변수를 위부에서 꺼낼 수 있게 메서드 자동 생성
@AllArgsConstructor //모든 변수를 파라미터로 받는 생성자 자동 생성
@Builder //빌더 패턴을 사용할 수 있게함 내가 넣고싶은 데이터만 골라 만들 수 있음
public class BoardResponse {

// 돌려주고 싶은 응답: id, title, content, writer, createdAt, updatedAt
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/com/likelion/session/dto/BoardUpdateRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

@Getter
@Setter
@NoArgsConstructor
@Getter //클래스 안의 변수들의 값을 외부에서 꺼내올 수 있게 메서드 자동 생성
@Setter //클래스 내부의 변수값을 변경할 수 있는 메서드 자동 생성
@NoArgsConstructor //파라미터가 하나도 없는 빈 생성자 생성
public class BoardUpdateRequest {
@NotBlank(message = "제목은 필수입니다.")
@Size(max = 100, message = "제목은 100자 이하로 입력해주세요.")
@NotBlank(message = "제목은 필수입니다.") //공백만 있거나 비어있는 경우 막아줌
@Size(max = 100, message = "제목은 100자 이하로 입력해주세요.") //글자수 제한
private String title;

@NotBlank(message = "내용은 필수입니다.")
@NotBlank(message = "내용은 필수입니다.") //공백만 있거나 비어있는 경우 막아줌
private String content;
}

14 changes: 7 additions & 7 deletions src/main/java/com/likelion/session/service/BoardService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
@Slf4j //로그를 남길 수 있게 함
@Service //비즈니스 로직을 담당하는 클래스임을 Spring에게 알려줌
@RequiredArgsConstructor //final이 붙은 필드를 위한 생성자 자동 생성, 의존성 주입
@Transactional //DB작업을 하나의 트랜잭션으로 묶어줌, 에러 발생 시 롤백
public class BoardService {

private final ;
private final BoardRepository boardRepository;

/*
게시글 생성
Expand Down Expand Up @@ -51,7 +51,7 @@ public BoardResponse create(BoardCreateRequest request) {
- DB에 있는 모든 게시글을 가져옴
- Entity 리스트를 Response DTO 리스트로 변환
*/
@Transactional(readOnly = true)
@Transactional(readOnly = true) //조회 전용 설정으로 성능 최적화에 씀
public List<BoardResponse> findAll() {
return boardRepository.findAll()
.stream()
Expand All @@ -71,7 +71,7 @@ public List<BoardResponse> findAll() {
- id로 게시글 조회
- 없으면 예외 발생
*/
@Transactional(readOnly = true)
@Transactional(readOnly = true) //조회 전용 설정으로 성능 최적화에 씀
public BoardResponse findById(Long id) {
Board board = boardRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("해당 게시글이 없습니다. id=" + id));
Expand Down
28 changes: 28 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
server:
port: 8082

spring:
application:
name: session

datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/session?serverTimezone=Asia/Seoul&characterEncoding=UTF-8
username: root
password: dmsco0504

jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true

jackson:
serialization:
fail-on-empty-beans: false

logging:
level:
org.hibernate.SQL: debug