스프링부트 + JPA + H2연결해서 사용하기
application properties 설정
서버 구동해보면 에러 뜸
연결하면 데이터 서버 관리창으로 들어감 - 별도 프로그램없이 db확인
dto역할을 하는 Board.java 만들기
package com.yuj.web;
import java.time.LocalDateTime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@NoArgsConstructor // 파라미터 없는 디폴트 생성자를 생성
public class Board {
@Id
@GeneratedValue
private int bno;
@Column(length = 50)
private String btitle;
@Column(columnDefinition = "mediumtext")
private String bcontent;
@Column
private LocalDateTime bdate = LocalDateTime.now();
@Column(nullable = false)
private String name;
@Builder
public Board(String btitle, String bcontent, String name) {
this.btitle = btitle;
this.bcontent = bcontent;
this.name = name;
}
}
컨트롤러
package com.yuj.web;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class H2Controller {
@Autowired
private H2Service h2Service;
}
서비스
package com.yuj.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class H2Service {
@Autowired
private BoardRepository boardRepository;
}
repository
package com.yuj.web;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BoardRepository extends JpaRepository<Board, Integer> { //타입 , PK의 타입
}
서버 다시 시작하면 구동되면서 데이터를 만들어줌 (Udate 모드)
다시 접속하면 생겨있음
에러는 났지만? 콘솔창 확인해보면
insert쿼리가 실행되어있음
콘솔창에 가보면 데이터 입력되어있음
board 페이지 만들기
board.html이 있어야 표시되겄지
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>board</h1>
<table>
<tr>
<th>번호</th>
<th>제목</th>
<th>날짜</th>
<th>작성자</th>
</tr>
<tr th:each="row : ${list}">
<td th:text="${row.bno}"></td>
<td th:text="${row.btitle}"></td>
<td th:text="${row.bdate}"></td>
<td th:text="${row.name}"></td>
</tr>
</table>
</body>
</html>
컨트롤러 수정
package com.yuj.web;
import java.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class H2Controller {
@Autowired
private H2Service h2Service;
@GetMapping("/board")
public String board(Model model) {
model.addAttribute("list", h2Service.findAll());
return "board";
}
@GetMapping("/insert")
public String insert() {
Board board = new Board("연습 1", "본문 1", "홍길동");
board.setBdate(LocalDateTime.now());
h2Service.insert(board);
return "redirect:/board";
}
}
이제 주소창에 locahost/insert 치면
데이터가 올라가고 게시판으로 이동됨