[Spring] Jpa Repository 사용하기

    [Spring] Jpa Repository 사용하기

    Entity

    데이터베이스에 저장하기 위하여 사용자가 정의한 클래스가 필요한데

    그 클래스를 Entity라고 한다.

     

    RDBMS에서 Table을 객체화 시킨 것

    @NoArgsConstructor
    @Getter
    @Entity
    @Setter
    
    public class Comment extends Timestamped {
    
        @GeneratedValue(strategy = GenerationType.Auto)
        @Id
        private Long id;
    
        @Column(nullable = false)
        private String comment;
    
        @Column(nullable = false)
        private Long poster_id;

    @Id

    해당 컬럼은 pk이며 @GeneratedValue 어노테이션은 해당 Id값을 어떻게 자동생성 할지 전략을 말한다.

     

    Repository

    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface CommentRepository extends JpaRepository<Comment, Long> {
    }

    Entity의 기본적인 CRUD가 가능하도록 JpaRepository 인터페이스를 기본적으로 제공하고 있으며,

    JpaRepository 인터페이스를 상속하기만 하면 된다.

     

    기본 기능

    method 기능
    findAll() 전체 레코드 불러오기(정렬, 페이징 가능)
    findOne() pk로 레코드 한건 찾기
    save() 레코드 저장(inster, update)
    count() 레코드 갯수
    delete() 레코드 삭제

    기본 기능 외에 다른 기능을 추가하고 싶으면 규칙에 맞게 메서드를 추가해주면 된다.

    ex)

    package com.example.mbti.repository;
    
    import com.example.mbti.model.Comment;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.repository.query.Param;
    
    import java.util.List;
    
    public interface CommentRepository extends JpaRepository<Comment, Long> {
        List<Comment> findByPoster_id(@Param("poster_id")Long poster_id);
    }

    findBy 메소드를 추가한 예시이다.

     

     

    2021.09.15 - [코딩/Spring Data Jpa] - [Jpa] Timestamped LocalDateTime format 변경

     

    [Jpa] Timestamped LocalDateTime format 변경

    [Jpa] Timestamped LocalDateTime format 변경 public abstract class TimeStamped { @CreatedDate // 최초 생성 시점 private LocalDateTime createdAt; 위와 같이 코드를 작성할 경우 표시되는 날짜 포맷은..

    alisyabob.tistory.com

     

    2021.09.15 - [코딩/Spring Data Jpa] - [Spring Data Jpa] Could not locate ordinal parameter [1], expecting one of []

     

    [Spring Data Jpa] Could not locate ordinal parameter [1], expecting one of [] 문제

    Could not locate ordinal parameter [1], expecting one of [] 문제 java.lang.IllegalArgumentException: Could not locate ordinal parameter [1], expecting one of [] at org.hibernate.query.inte..

    alisyabob.tistory.com

     

    2021.09.15 - [코딩/node.js] - node.js를 활용한 Http-server 구축

     

    node.js를 활용한 Http-server 구축

    node.js를 활용한 Http-server 구축 리액트-스프링 프로젝트를 했을때 iptime을 통하여 외부에서 내pc에 접근이 가능하게 배포를 한적이 있는데 이때 사용한 방법이다. 2020.01.05 - [생활정보] - 이클립

    alisyabob.tistory.com

     

    댓글

    Designed by JB FACTORY