[뭐라도 해야지...] Post관련 CRUD api 작성하기. 1)

Post Entity클래스 작성

패키지 관리

저는 domain 패키지 안에 entity가 되는 클래스의 이름으로 패키지를 하나 더 생성 후에 작업합니다.

Post 클래스 작성하기

package com.momenting.todosomething.domain.post;

import com.momenting.todosomething.domain.BaseTimeEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;

@Getter
@NoArgsConstructor
@Entity(name = "tbl_post")
public class Post  extends BaseTimeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "pidx")
    private Long id;

    @Column(columnDefinition = "TEXT",nullable = false)
    private String pcontent;

    @Column(length = 100, nullable = false)
    private String writer;

    @Column(columnDefinition = "ENUM('y','n')")
    @Enumerated(EnumType.STRING)
    private Secret secret;

    @Builder
    public Post(String pcontent, String writer, Secret secret) {
        this.pcontent = pcontent;
        this.writer = writer;
        this.secret = secret;
    }

    public void update(String pcontent, Secret secret) {
        this.pcontent = pcontent;
        this.secret = secret;
    }
}

Secret Enum 작성

package com.momenting.todosomething.domain.post;

public enum Secret {
    y, n;
}

PostRepository 인터페이스 작성

package com.momenting.todosomething.domain.post;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface PostRepository extends JpaRepository<Post, Long> {

    @Query("select p from tbl_post p order by p.id desc")
    List<Post> findAllDesc();
}

Jpa Auditing으로 생성, 수정 시간 괸리하는 BaseTimeEntity 추상 클래스 작성

package com.momenting.todosomething.domain;

import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;

@Getter
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseTimeEntity {
    @CreatedDate
    @Column(name = "regdate")
    private LocalDateTime regDate;

    @LastModifiedDate
    @Column(name = "updatedate")
    private  LocalDateTime updateDate;
}

좋은 웹페이지 즐겨찾기