키보드워리어

[스프링] 자동 생성일,수정일 만들기 본문

Spring framework/JPA

[스프링] 자동 생성일,수정일 만들기

꽉 쥔 주먹속에 안경닦이 2023. 4. 25. 10:39
728x90

안녕하세요 【키보드 워리어】 블로그 방문자 여러분, 안경닦이입니다.

오늘은 Auditing기능으로 자동 생성일, 수정일을 만들어 보도록 할게요.

 


Auditing기능은 모든 Entity의 상위 클래스로 상속받게 하여 createdDate, ModifiedDate자동 관리가 됩니다.

//모든 Entity의 상위 클래스로 createdDate,ModifiedDate자동 관리
//Application 클래스에 @EnableJpaAuditing 지정
@Getter
@MappedSuperclass
//Entity클래스들이 BaseTimeEntity 를 상속하면 필드 멤버도 컬럼으로 인식
@EntityListeners(AuditingEntityListener.class)//Auditing기능 자동 포함
public class BaseTimeEntity {
    @CreatedDate
    private LocalDateTime createdDate;

    @LastModifiedDate
    private LocalDateTime modifiedDate;

}

 

스프링에서는 @CreatedDate나 @LastModifiedDate 기능을 지원해주니 편합니다.

 

그리고 만든 entity클래스에 상속을 해주세요.

 

public class Posts extends BaseTimeEntity {

그리고 PostsListResponseDto 클래스를 아래처럼 꾸며볼게요

@Getter
public class PostsListResponseDto {
    private Long id;
    private String title;
    private String author;
    private LocalDateTime modifiedDate;


    public PostsListResponseDto(Posts entity){
        this.id = entity.getId();
        this.title = entity.getTitle();
        this.author = entity.getAuthor();
        this.modifiedDate = entity.getModifiedDate();
    }
}

 

잠깐!) Entity를 쓰지 않고 Dto를 쓰는 이유는?

2023.04.21 - [개발 관련/어려웠던것들] - [Springframework] Dto개념 익히기

 

[Springframework] Dto개념 익히기

안녕하세요 【키보드 워리어】 블로그 방문자 여러분, 안경닦이입니다. 스프링 개발을 하면서 생소했던 개념인 Dto에 대해 적어보려고 합니다. @Getter @RequiredArgsConstructor//final 필드값 생성자 형성

keyboardwarrior.tistory.com

 
Dto를 쓰기위해 Service 레이어에 등록해보죠
@Service
public class PostsService{
@Transactional(readOnly = true) //조회기능만 남겨두어 속도 향상
    public List<PostsListResponseDto> findAllDesc(){
return postsRepository.findAllDesc().stream()
        .map(PostsListResponseDto::new).
        collect(Collectors.toList());
    }
}
 

Controller를 통해 화면에 띄워 볼게요. h2 콘솔을 통해 볼 수도 있긴 하죠.

@RequiredArgsConstructor
@Controller
public class IndexController {

    private final PostsService postsService;

@GetMapping("/")
    public String index(Model model){
        model.addAttribute("posts",postsService.findAllDesc());
        return "index";
    }//객체 저장할 수 있음
}

html파일을 만들어 보겠습니다. thymleaf 문법입니다.

    <table class="table table-horizontal table-bordered">
            <thead class="thead-strong">
            <tr>
                <th>게시글번호</th>
                <th>제목</th>
                <th>작성자</th>
                <th>최종수정일</th>
            </tr>
            </thead>
            <tbody id="tbody">
            <tr th:each="post : ${posts}">
                <td th:text="${post.id}"></td>
                <td><a th:href="@{/posts/update/{id}(id=${post.id})}" th:text="${post.title}"></a></td>
                <td th:text="${post.author}"></td>
                <td th:text="${post.modifiedDate}"></td>
            </tr>
            </tbody>
        </table>

최종수정일이 포함되었다.
최종수정일이 포함되었다.
생성일, 수정일

최종 수정일 modifiedDate를 사용하여서 출력을 만들어 보았습니다.

 

728x90