Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- JShell
- 메소드
- 컴퓨터과학개론
- 배열
- 리눅스
- 초보코딩탈출
- JAVA기초
- 데이터베이스
- 클래스
- 제이쉘
- spring
- 자바 스프링
- 코딩초보
- 프로그래밍기초
- Elk
- eclips
- 초보코딩
- 자바프로그래밍
- 스프링 기초
- 프로그래밍언어
- 자바기초
- 스프링
- github
- 알고리즘
- Java
- Git
- 이클립스
- 프로그래밍
- 기초코딩
- 자바
Archives
- Today
- Total
키보드워리어
[스프링] 자동 생성일,수정일 만들기 본문
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개념 익히기
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
'Spring framework > JPA' 카테고리의 다른 글
[스프링]1:N 관계 ERR 다이어그램과 자바 코드로 표현 *카디널러티 (0) | 2023.04.18 |
---|---|
[스프링] @Entity와 @Component의 차이 (0) | 2023.04.14 |