스프링부트_JPA_H2

 

H2_build.gradle ( dependencies )

implementation 'org.springframework.boot:spring-boot-starter-jdbc' // Jdbc, Driver
    implementation 'com.h2database:h2' // h2 : implementation
    //runtimeOnly 'com.h2database:h2'

 

 

application.properties

spring.h2.console.enabled=true
#H2 URL 주소
spring.h2.console.path=/h2-console
#JDBC URL
spring.datasource.url=jdbc:h2:mem:test;
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

 

@Entity

package com.example.demo.entity;

import lombok.*;

import javax.persistence.*;

@Entity
@Table(name="mydata")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class MyData {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column
    private Long id;

    @Column(length = 50, nullable = false)
    private String name;

    @Column(length = 200, nullable = true)
    private String mail;

    @Column(nullable = true)
    private int age;

    @Column(nullable = true)
    private String memo;

}

 

인터페이스 Jpa 상속

package com.example.demo.repository;

import com.example.demo.entity.MyData;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MyDatarepository extends JpaRepository<MyData, Long> {
}

 

 

cotroller에서 데이터 넣어서 테스트 해보기

    @PostConstruct
    public void init(){

        MyData d1 = new MyData();
        d1.setName("kim");
        d1.setAge(123);
        d1.setMail("kim@gitbut.co.kr");
        d1.setMemo("this is my data!");
        myDatarepository.saveAndFlush(d1);

        MyData d2 = new MyData();
        d2.setName("lee");
        d2.setAge(15);
        d2.setMail("lee@gitbut.co.kr");
        d2.setMemo("my girl my data!");
        myDatarepository.saveAndFlush(d2);

        MyData d3 = new MyData();
        d3.setName("choi");
        d3.setAge(33);
        d3.setMail("choi@gitbut.co.kr");
        d3.setMemo("my boy!");
        myDatarepository.saveAndFlush(d3);

    }

 

 

 

타임리프( thymeleaf ), JSP ( JPA, @Entity는 기존꺼 사용 ) 

 

dependencies

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

 

application.properties

#JSP
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

#타임리프
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.view-names=th/*

 

controller

package com.example.demo.controller;

import com.example.demo.entity.MyData;
import com.example.demo.repository.MyDatarepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.PostConstruct;
import java.util.Optional;

@Controller
public class MyController {

   @Autowired
    MyDatarepository myDatarepository;
    
   // static
    @GetMapping("/main")
    public String index(Model model){
        model.addAttribute("list", myDatarepository.findAll());
        return "th/index";
    }
    
    //타임 리프
    @GetMapping("/test1")
    public String test1(Model model){
        model.addAttribute("msg", "테스트 자료");
        return "th/index2";
    }
    
    // 타임리프
    @GetMapping("/data/{id}")
    public String index3(@PathVariable Long id,
    Model model){
        Optional<MyData> myData = myDatarepository.findById(id);
        MyData data = myData.get();
        model.addAttribute("msg", "id");
        model.addAttribute("object", data);
        System.out.println("-------------------"+myData.get());
        return "th/index3";
    }

    // JSP
    @GetMapping("/list")
    public String list(Model model){
        model.addAttribute("list", myDatarepository.findAll());
        return "list";
    }
    }

 

 

 

/list ( list.JSP )

 

<%--
  Created by IntelliJ IDEA.
  User: 1
  Date: 2023-09-14
  Time: 오전 11:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>list.jsp</h1>

<c:forEach var="dto" items="${list}">

    <li>${dto.name}, ${dto.mail}</li>

</c:forEach>
</body>
</html>

 

 

resources => static ( 타임리프 )

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>static 처음페이지</h1>
</body>
</html>

 

타임 리프 ( 자료형식 출력 해보기 ) / test1

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>index2.html</h1>

<p th:text="${#dates.format(new java.util.Date(),'dd/MM/yyyy HH:mm')}"></p>
<p th:text="${#numbers.formatInteger(1234,7)}"></p>
<p th:text="${#strings.toUpperCase('Welcome')}"></p><br/>

<input type="text" th:value="${msg}" /><br/>

<p class="msg" th:text="${msg}"></p>

<p>[[${msg}]]</p>
</body>
</html>

 

타임리프 ( id값 가져와서 테이블 출력 ) / index3

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>top page</title>
    <meta http-equiv="Content-Type"
          content="text/html; charset=UTF-8" />
    <style>
        h1 { font-size:18pt; font-weight:bold; color:gray; }
        body { font-size:13pt; color:gray; margin:5px 25px; }
        tr { margin:5px; }
        th { padding:5px; color:white; background:darkgray; }
        td { padding:5px; color:black; background:#e0e0ff; }
    </style>
</head>
<body>
<h1 th:text="#{content.title}">Helo page</h1>
<p th:text="${msg}">message.</p>
<table th:object="${object}">
    <tr><th>ID</th><td th:text="*{id}"></td></tr>
    <tr><th>NAME</th><td th:text="*{name}"></td></tr>
    <tr><th>MAIL</th><td th:text="*{mail}"></td></tr>
</table>
</body>
</html>

'프로젝트 기반 자바(JAVA) 응용 SW개발자 취업과정' 카테고리의 다른 글

2023-09-15 84일차  (0) 2023.09.21
2023-09-13 82일차  (0) 2023.09.13
2023-09-12 81일차  (0) 2023.09.12
2023-09-11 80일차  (0) 2023.09.11
2023-09-08 79일차  (0) 2023.09.08

+ Recent posts