1. Spring Data JPA 게시판(1)
- 게시판 리스트 보기
- SPRING BOOT, ORACLE
TOPCREDU.CO.KR 이종철
2. 1. 개요
JPA로 게시판을 만든다는 것은 맞지 않을 수도 있지만 기능과 사용방법을 익힌다
는 관점에서 간단히 만들어 보자. 본예제는 오라클 DB를 기준으로 작성되었으며
MySQL(MariaDB) 예제는 다음 URL에서 참조하면 된다.
http://ojc.asia/bbs/board.php?bo_table=LecJpa&wr_id=244
글리스트 보기
구현기술
Spring Boot, Spring WEB MVC, RestController
Spring Data JPA(Hibernate)
기본 JpaRepository
Query Method
Oracle DataBase
UI : JSP, BootStrap, AngularJS, JSON
Logging: DriverSpy www.topcredu.co.kr
3. 2. TABLE 및 SEQUENCE - 1
테이블 및 시퀀스는 엔티티를 정의해서 자동 생성시킬 예정이니 DB쪽에 생성할 필요
없다. 구조만 확인하자.
Board 테이블의 PK(ID칼럼, Primary Key)는 오라클 시퀀스를 이용할 것이다. MySQL이
라면 자동증분 칼럼을 사용하니 특별히 생성할 필요 없다.(본 예제는 오라클을 기준으
로 한다.)
엔티티를 만들 때 키 부분(ID칼럼)에 어노테이션 사용하는 것만 DB가 무엇이냐에 따
라 좀 다르니 확인하면 된다.
www.topcredu.co.kr
4. 2. TABLE 및 SEQUENCE - 2
create table board (
id number(10,0) not null,
content varchar2(4000 char) not null,
name varchar2(20 char) not null,
passwd varchar2(20 char) not null,
readcount number(5) default 0 not null,
regdate date default sysdate not null,
-- 답변인경우 어느글의 답변인지 상위글 번
호,최상위글인 경우 자신의 글번호 동일,
-- 리스트보기에서 정렬시 우선 reply로 우
선하게 된다.
reply number(5) not null,
-- 하나의 글 아래에 생기는 모든 답변들에 대해
순차적으로 1씩 증가(reply_level과 관계없이)
replylevel number(5) default 0 not null,
-- 1차,2차 답글인지 여부, 글에 답변이 두개면
그 두답변은 reply_level이 같다.
-- 리스트보기에서 reply_level에 따라 들여쓰기
를 한다.
replystep number(5) default 0 not null,
title varchar2(500 char) not null,
primary key (id)
)
create sequence BOARD_SEQ;
JPA에서 자동생성한 DDL 스크립트
www.topcredu.co.kr
5. 3. 프로젝트 생성 및 메이븐 설정, 로깅,
오라클 설정 - 1
STS -> Spring Starter Project
Name : jpaboard
Group : ojc.asia
Artifact : jpaboard
Description : Spring Data JPA Board
pckage : jpa.board 입력
다음 창에서
Core : Lombok
SQL : JPA
Web : Web 선택
www.topcredu.co.kr
6. 3. 프로젝트 생성 및 메이븐 설정, 로깅,
오라클 설정 - 2
www.topcredu.co.kr
www.topcredu.co.kr
12. 8. board.java - 1
@Column(length=20, nullable=false)
protected String name;
@Column(length=20, nullable=false)
protected String passwd;
@Column(length=500, nullable=false)
protected String title;
@Column(length=4000, nullable=false)
protected String content;
//날짜기본형식 time, day, month, year 형태저장
@Column(nullable=false, columnDefinition = "date default
sysdate")
@Temporal(TemporalType.TIMESTAMP)
protected Date regdate = new Date();
@Column(nullable=false, columnDefinition = "number(5)
default 0")
protected Integer readcount = 0;
package jpa.board.model;
@Entity @Getter @Setter
// 시퀀스의 시작값은 1
// 시퀀스의 기본 allocationSize는50, 번호가 50부터 생기므로
1로
@SequenceGenerator(name="BOARD_SEQ_GENERATOR",
sequenceName="BOARD_SEQ",
initialValue=1, allocationSize=1)
public class Board {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,
generator="BOARD_SEQ_GENERATOR") @Column(length=10)
protected Integer id;
13. 8. board.java - 2
// 1차,2차 답글인지 여부
// 하나의 글에 답변이 두개면 그 두답변은 reply_level이
같다.
// 리스트보기에서 reply_level에 따라 들여쓰기를 한다.
@Column(nullable=false,columnDefinition =
"number(5) default 0", length=10)
protected Integer replylevel = 0;
}
// 답변인경우 어느글의 답변인지 상위글번호
// 최상위글인 경우 자신의 글번호 동일하다.
// 리스트보기에서 정렬시 우선적으로 reply로 정렬
@Column(nullable=false, columnDefinition =
"number(5)")
protected Integer reply = 0 ;
// 글아래 모든 답변들에 대해 reply_level과 관계없이 1
씩 증가
@Column(nullable=false, columnDefinition = "number(5)
default 0")
protected Integer replystep = 0;
프로젝트에서 마우스 우측버튼 -> Run As ->
Spring Boot App로 실행 후 오라클쪽에 테이
블이 생성되는 것을 확인하자.
www.topcredu.co.kr
14. 9. 게시판리스트 보기 - 1
Spring JDBC 또는 MyBatis로 만들 때 보다 쉽고
빠르게 작성할 수 있다.
스프링 컨트롤러는 RestController를 적용 했으
며, 뷰 페이지에 Bootstrap 및 AngulerJS 적용했
다.
프로젝트 전체 구조는 다음과 같다.
www.topcredu.co.kr
15. 9. 게시판리스트 보기(BoardRepository.java) - 2
기본적으로 제공하는 JpaRepository를 상속받아 만들면 된다.
JpaRepository는 PagingAndSortingRepository를 상속받았고
PagingAndSortingRepository는 CrudRepository(기본적인 CRUD 기능을 제공한다)를
상속 받았으며 다시 CrudRepository는 Repository 인터페이스를 상속받았다.
그러므로 JpaRepository는 모든 기능을 다 사용할 수 있고 추가적으로 영속성 컨텍스
트에 flush하거나 엔티티를 배치로 삭제할 수 있다.
기본 기능만으로도 게시판 기능을 구현할 수 있으므로 JpaRepository를 상속 받자.
www.topcredu.co.kr
package jpa.board.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import jpa.board.model.Board;
public interface BoardRepository extends JpaRepository<Board, Integer> {
}
16. 9. 게시판리스트 보기(BoardService.java) - 3
www.topcredu.co.kr
package jpa.board.service;
import org.springframework.data.domain.Page;
import jpa.board.model.Board;
public interface BoardService {
//게시판 리스트 보기
public Page<Board> findAll(Integer curPage);
}
17. 9. 게시판리스트 보기(BoardServiceImpl.java) - 4
JpaRepository의 findAll() 메소드를 호출만 하면 되는데 페이징 기능을 구현하기 위해
PageRequest를 만들고 이를 findAll() 메소드의 인자로 넣어주면 된다.
Board 테이블에서 정렬한 칼럼이 두개 이상이므로 Sort 를 new하면서 Order를 필요
한 만큼 생성해주면 되고 ASC는 오름차순, DESC는 내림차순, 그뒤의 문자열은 Board
엔티티의 속성이다.
www.topcredu.co.kr
package jpa.board.service;
@Service
public class BoardServiceImpl implements
BoardService {
@Autowired
BoardRepository boardRepository;
@Override
//-----------------------------------------
// 게시판 리스트 보기, 한페이지에 3개씩
// curPage:요청하는 페이지, 첫페이지는 0
//-----------------------------------------
public Page<Board> findAll(Integer curPage) {
PageRequest pr = new PageRequest(curPage, 3,
new Sort(
new Order(Direction.DESC, "reply"),
new Order(Direction.ASC, "replystep")));
return boardRepository.findAll(pr);
}
}
18. 10. 컨트롤러(BoardController.java)
www.topcredu.co.kr
package jpa.board.controller;
@RestController
@RequestMapping("/board")
public class BoardController {
@Autowired
BoardService boardService;
//---------------------------------------------
// 루트요청(localhost:8080/board/)시 리스트 보기
로
//---------------------------------------------
@RequestMapping(method = RequestMethod.GET)
public ModelAndView index() {
//jsp아래 board.jsp 호출
return new ModelAndView("board");
}
//---------------------------------------------
// 게시판 리스트 보기
//---------------------------------------------
@RequestMapping(value="/{curPage}", method =
RequestMethod.GET)
public ResponseEntity<Page<Board>> list(Model model,
Pageable pageable, @PathVariable Integer curPage) {
Page<Board> page = boardService.findAll(curPage);
return new ResponseEntity<Page<Board>>(page,
HttpStatus.OK);
}
}