Spring Boot + JPA

jooog·2021년 11월 2일
0

스프링

목록 보기
5/26

jpa를 사용해서 간단하게 자바객체와 테이블을 매핑해보자

데이터베이스는 마리아디비(mariadb)를 사용한다.

Board 객체 생성

package hello.itemservice.model;


import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Data
public class Board {

    //primarykey
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;
}

@Entity 어노테이션으로 테이블을 생성한다.

primarykey를 지정해주기 위해 @Id 어노테이션을 추가한다.

@GeneratedValue 어노테이션을 사용하면 id 값이 자동으로 증가한다.

BoardRepository 생성

package hello.itemservice.repository;
import hello.itemservice.model.Board;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

public interface BoardRepository extends JpaRepository<Board, Long> {} 

스프링부트에서 자동으로 생성해준 BoardRepository를 사용할 수 있다.

@Autowired
private BoardRepository boardRepository;

boardRepository.save();
boardRepository.findById();
@Controller
@RequestMapping("/board")
public class BoardController {

    @Autowired
    private BoardRepository boardRepository;

    //페이지 표시하기
    @GetMapping("/list")
    public String list(Model model, @PageableDefault(size = 2) Pageable pageable){
         Page<Board> boards = boardRepository.findAll(pageable);
         //boardrepository에서 찾아온다

         int startPage = Math.max(1, boards.getPageable().getPageNumber() -4);
         int endPage = Math.min(boards.getTotalPages(), boards.getPageable().getPageNumber() +4);
         model.addAttribute("startPage", startPage);
         model.addAttribute("endPage", endPage);
         model.addAttribute("boards", boards);
        return "board/list";
    }

model에 찾아온 boards 데이터를 넣어주고 페이징처리까지 한 다음에 return으로 list html파일을 호출해준다.

board 데이터 출력

<div class="container" style="margin-top: 5rem">
    <div class="py-5 text-center">
        <p style="font-size: 4rem; text-align: left">게시판</p>
        <div style="font-size: 2rem; text-align: left">총 건수: <span th:text="${boards.totalElements}"></span></div>
        <div style="text-align: right"><a th:href="@{/board/form}"><button class="btn btn-info" style="font-size: 2rem">글쓰기</button></a></div>
    </div>

    <table class="table table-striped" style="font-size: 2rem">
        <thead>
        <tr>
            <th scope="col">번호</th>
            <th scope="col">제목</th>
            <th scope="col">내용</th>

        </tr>
        </thead>
        <tbody>
        <tr th:each="board: ${boards}" style="font-size: 1.8rem">
            <td th:text="${board.id}"></td>
            <td>
                <a th:text="${board.title}" th:href="@{/board/form(id=${board.id})}"></a>
            </td>
            <td th:text="${board.content}"></td>

        </tr>

        </tbody>
    </table>

이제 데이터베이스 테이블을 만들었으니 controller 작업을 해보자.

localhost:8080/board/list

@Controller
@RequestMapping("/board")
public class BoardController {

 @Autowired
 private BoardRepository boardRepository;
 
 @GetMapping("/list")
 public String list(Model model){
    List<Board> boards = boardRepository.findAll();
     //boardrepository에서 찾아온다

    model.addAttribute("boards", boards);
    return "board/list";
        
    }

}

이제 localhost:8080/board/list 로 요청이오면
board 테이블에 담긴 데이터가 화면에 출력된다.

0개의 댓글