public class Board {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@SequenceGenerator(sequenceName = "board_boardno_seq", name = "board_boardno_seq")
private Long boardno;
private String title;
private String writer;
private String content;
@ColumnDefault("sysdate")
@CreationTimestamp
private LocalDateTime regdate;
private Long readcount;
private Long groupno;
private Long step;
private Long depth;
}
@UpdateTimestamp도 있어서 update시 regdate에 time을 넣어줄 수 있지만
CreationTimestamp와 중복하여 사용할 수 없다.
사용하려면 updatedate 필드를 만들어서 붙여야 한다.
@ColumnDefault 어노테이션은 jpa에서 insert할 때는 무시한다.
하지만 sql을 사용할때는 적용되기 때문에 붙여준다.
Repository
List<Board> findByStepGreaterThanAndGroupno(Long step,Long groupNo);
List<Board> findByBoardnoGreaterThanEqualOrderByGroupnoDescStepAsc(Long boardNo);
//Page<Board> findByBoardnoGreaterThanEqualOrderByGroupnoDescStepAsc(Long boardNo,Pageable pageable);
new_save() 새글 작성하기
void new_save() {
Board board1= Board.builder()
.title("게시판101")
.content("내용101")
.writer("101")
.build();
Board savedBoard1 = boardRepository.save(board1);
savedBoard1.setGroupno(savedBoard1.getBoardno());
savedBoard1.setStep(1L);
savedBoard1.setDepth(0L);
savedBoard1.setReadcount(0L);
savedBoard1= boardRepository.save(savedBoard1);
System.out.println(">>>savedBoard1:"+savedBoard1);
답글 작성
void reply_save() {
Board findBoard100 = boardRepository.findById(100L).get();
List<Board> updateBoardList100 =
boardRepository.findByStepGreaterThanAndGroupno(findBoard100.getStep(), findBoard100.getGroupno());
for (Board tempBoard : updateBoardList100) {
tempBoard.setStep(tempBoard.getStep()+1);
}
boardRepository.saveAll(updateBoardList100);
Board board101=Board.builder()
.title("게시판타이틀101")
.content("내용101")
.writer("김경호101")
.groupno(findBoard100.getGroupno())
.step(findBoard100.getStep()+1)
.depth(findBoard100.getDepth()+1)
.readcount(0L)
.build();
boardRepository.save(board101);
그룹넘버가 같고 step이 더 큰 글(답글을 달려는 원글의 답글들 , 원글이 답글이 될 수도 있다)에 step을 증가시킴
board101 글을 원글보다 step, depth를 증가시키고 save
void board_select() {
List<Board> boardList = boardRepository.findAll();
for (Board board : boardList) {
System.out.println(board);
}
boardList = boardRepository.findByBoardnoGreaterThanEqualOrderByGroupnoDescStepAsc(0L);
for (Board board : boardList) {
System.out.println(board);
}
글 목록 전체 조회
list를 groupno 내림차순, step 오름차순으로 정렬하여 select
orderBy 할때 앞에 조건문이 필요하여 BoardnoGreaterThanEqual 추가해주고 0L인자로 준다.
페이징 작업
void board_select_page() {
List<Board> boardList=boardRepository.findAll();
System.out.println(">>>boardList:"+boardList.size());
int currentPage=14; //현재페이지
int size=7; //페이지당게시물수
Pageable pageable=PageRequest.of(currentPage-1,
size,
Sort.by("groupno").descending()
.and(Sort.by("step").ascending())
);
/*
PageRequest.of(page, size)
- page zero-based page index.(요청페이지)
- size the size of the page to be returned.(페이지당 게시물 수)
*/
Page<Board> page = boardRepository.findAll(pageable);
for (Board board : page.getContent()) {
System.out.println(board);
}
}
Pageable 인터페이스
- pageNumber: 페이지 번호를 나타냅니다. 0부터 시작하며 첫 번째 페이지는 0입니다. 이 속성은 몇 번째 페이지를 가져올지를 결정합니다.
- pageSize: 한 페이지에 표시될 항목 수를 나타냅니다. 예를 들어, 페이지당 10개의 항목을 표시하려면 pageSize를 10으로 설정합니다.
- offset: 페이지의 시작 항목의 오프셋입니다. 이것은 pageNumber * pageSize의 값과 같습니다. 데이터베이스 쿼리를 작성할 때 특정 페이지의 데이터를 가져오는 데 사용됩니다.
- sort: 페이지의 항목을 정렬하는 데 사용됩니다. Sort 타입의 객체로 정렬 방법과 정렬할 필드를 지정할 수 있습니다. 다음은 Sort를 사용하는 예입니다.이것은 "fieldName" 필드를 오름차순으로 정렬하는 방법을 나타냅니다.
Sort sort = Sort.by(Sort.Order.asc("fieldName"));
- unpaged(): 페이지네이션을 사용하지 않고 모든 데이터를 한 번에 가져오도록 지정합니다. 주로 모든 데이터를 가져올 때 사용됩니다.
- next(): 다음 페이지로 이동하는 Pageable 객체를 생성합니다.
- previousOrFirst(): 이전 페이지로 이동하거나 첫 번째 페이지로 이동하는 Pageable 객체를 생성합니다.
- first(): 첫 번째 페이지로 이동하는 Pageable 객체를 생성합니다.
- hasNext(): 다음 페이지가 있는지 확인합니다.
- getSort(): 현재 페이지에 적용된 정렬 정보를 가져옵니다.
Pageable 인터페이스는 데이터베이스 조회 결과를 정렬하고 페이지를 나누고 그 페이징 관련 정보를 담고 있다.
Pageable pageable=PageRequest.of(currentPage-1,
size,
Sort.by("groupno").descending()
.and(Sort.by("step").ascending())
);
PageRequest의 of (page,size)메서드를 사용하면 페이지를 전체 리스트를 size로 나누어 페이징했을 때 구한 page의 paging 정보를 Pageable 인터페이스로 반환해준다.
추가로 page,size, Sort(정렬)을 대입할 수도 있다.
Sort.by("groupno").descending().and(Sort.by("step").ascending())
findAll 메서드에 Pageable을 인자로 대입하면 해당 Pageable의 Page를 반환해주고
Page의 getContent 하여 리스트를 얻을 수 있다.
반대로 Page에서 getPageable 을 하면 Pageable을 얻을 수 있다.
- getContent(): 페이지에 포함된 데이터 항목들을 반환합니다. 이 메서드를 통해 현재 페이지의 데이터를 가져올 수 있습니다.
- getNumber(): 현재 페이지 번호를 반환합니다. 페이지 번호는 0부터 시작합니다.
- getSize(): 페이지 크기(한 페이지 당 항목 수)를 반환합니다.
- getTotalPages(): 전체 페이지 수를 반환합니다.
- getTotalElements(): 전체 항목 수를 반환합니다. 이는 모든 페이지를 합친 총 데이터 항목 수입니다.
- hasContent(): 페이지에 데이터가 포함되어 있는지 여부를 확인합니다.
- hasNext(): 다음 페이지가 있는지 여부를 확인합니다.
- hasPrevious(): 이전 페이지가 있는지 여부를 확인합니다.
- isFirst(): 현재 페이지가 첫 번째 페이지인지 여부를 확인합니다.
- isLast(): 현재 페이지가 마지막 페이지인지 여부를 확인합니다.
- nextPageable(): 다음 페이지로 이동하는 데 필요한 Pageable 객체를 반환합니다.
- previousPageable(): 이전 페이지로 이동하는 데 필요한 Pageable 객체를 반환합니다.
'Java > Spring Boot' 카테고리의 다른 글
Thymeleaf Layout (1) | 2023.11.24 |
---|---|
JPA Object Relation Mapping (0) | 2023.10.11 |
Spring Data JPA begins (0) | 2023.10.06 |
Spring CRUD with RestAPI (0) | 2023.09.20 |
Spring addViewControllers (0) | 2023.09.14 |