그저 내가 되었고
🌱Spring Data JPA 기본 사용법 본문
개인 공부 후 정리 용도의 글입니다.
틀린 내용이 많을 확률이 적지 않습니다.
피드백 환영합니다.
1. dependency 등록(전 Maven 사용해서 pom.xml에 등록했습니다)
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
2. Model - DAO 생성(Entity/도메인 객체)
* DAO(Data Access Object):
package com.swchoi.webservice.springboot.domain.posts;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Getter
@NoArgsConstructor
@Entity
public class Comment extends BaseTimeEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String comment;
@Column(nullable = false)
private Long postId;
public Comment(CommentDto commentDto){
this.comment = commentDto.getComment();
this.postId = commentDto.getPost_id();
}
public void update(CommentDto commentDto){
this.comment = commentDto.getComment();
}
}
@Entity
- 테이블과 링크될 클래스임을 나타낸다.
- 기본값으로 크래스의 카멜케이스 이름을 언더 스커어 네이밍(_)으로 테이블 이름을 매칭
- ex) SalesManager.java -> sales_manager table
3. Model - Repository 생성
public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findAllByPostId(Long post_id);
}
JPA에선 Repository라고 불리는 DB Layer 접근자이나 ibatis나 MyBatis 등에서 DAO라고 불림.
인터페이스로 생성한 후 JpaRepository<Entity 클래스, PK 타입>을 상속하면 기본적인 CRUD 메소드가 자동으로 생성된다.
- @Repository를 추가할 필요 없다.
- Entity 클래스와 기본 Entity Repository는 함께 위치해야 한다.
+)
JPA는 메소드 이름만으로 쿼리를 생성할 수 있다.
위에서 작성한 List<Comment> findAllByPostId(Long post_id); 해당 구문을 보면 해석해 보면 findAll(comment) 전부 찾아볼건데 postId로 찾는다는 거다. 이렇게만 작성해주면 JPA가 알아서 SQL문을 생성해준다.
4. Controller에서 Get Mapping
@GetMapping("/api/comment/{id}")
public List<Comment> listComment(@PathVariable Long id){
return commentService.findAllCommentsByPostId(id);
}
5. Service
@RequiredArgsConstructor
@Service
public class CommentsService {
private final CommentsRepository commentsRepository;
public findAllCommentsByPostId(Long id) {
return commentsRepository.findAllByPostId(id);
}
}
참고::
'개발 > Spring' 카테고리의 다른 글
🌱Spring/LOMBOK:: @NOARGSCONSTRUCTOR , @ALLARGSCONSTRUCTOR , @REQUIREDARGSCONSTRUCTOR / DI (0) | 2023.05.11 |
---|---|
🌱Spring 프로젝트 설계 순서 (0) | 2023.04.19 |
🌱Spring 패키지 구조(Entity, DTO, DAO, Controller, Service, Repository) + DTO를 굳이 사용하는 이유 (0) | 2023.04.11 |
🌱실무에서의 Spring 프로젝트 폴더 설계(by. 우아한형제들 기술이사 김영한 개발자님) (0) | 2023.04.11 |
🌱'의존성 문제'란 무엇일까~요? (0) | 2023.04.06 |