Spring BootとJPA 1(Webアプリケーション開発)1-プロジェクト優先パラメータを利用


(1)プロジェクトの作成

  • プロジェクト
  • の作成
    스프링 부트 스타터(https://start.spring.io/)
    - 사용 기능: web, thymeleaf, jpa, h2, lombok, validation
    - groupId: jpabook
    - artifactId: jpashop
  • build.gradle
  • plugins {
    id 'org.springframework.boot' version '2.4.1'
    id 'io.spring.dependency-management' version '1.0.10.RELEASE'
    id 'java'
    }
    group = 'jpabook'
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = '11'
    configurations {
    compileOnly {
    extendsFrom annotationProcessor
    }
    }
    repositories {
    mavenCentral()
    }
    dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    //JUnit4 추가
    testImplementation("org.junit.vintage:junit-vintage-engine") {
    exclude group: "org.hamcrest", module: "hamcrest-core"
    }
    }
    test {
    useJUnitPlatform()
    }

    (2)リポジトリの表示

  • 勾配依存
  • を表示
    ./gradlew dependencies —configuration compileClasspath
  • スプリングガイドライブラリ
  • を表示
    spring-boot-starter-web
    - spring-boot-starter-tomcat: 톰캣 (웹서버)
    - spring-webmvc: 스프링 웹 MVC
    
    spring-boot-starter-thymeleaf: 타임리프 템플릿 엔진(View)
    
    spring-boot-starter-data-jpa
    - spring-boot-starter-aop
    - spring-boot-starter-jdbc
      - HikariCP 커넥션 풀 (부트 2.0 기본)
    - hibernate + JPA: 하이버네이트 + JPA
    - spring-data-jpa: 스프링 데이터 JPA
    
    spring-boot-starter(공통): 스프링 부트 + 스프링 코어 + 로깅
    - spring-boot
      - spring-core
    - spring-boot-starter-logging
      - logback, slf4j
      
    테스트 라이브러리 
    spring-boot-starter-test
    - junit: 테스트 프레임워크
    - mockito: 목 라이브러리
    - assertj: 테스트 코드를 좀 더 편하게 작성하게 도와주는 라이브러리
    - spring-test: 스프링 통합 테스트 지원
    
    핵심 라이브러리
    - 스프링 MVC
    - 스프링 ORM
    - JPA, 하이버네이트
    - 스프링 데이터 JPA
    
    기타 라이브러리
    - H2 데이터베이스 클라이언트
    - 커넥션 풀: 부트 기본은 HikariCP
    - WEB(thymeleaf)
    - 로깅 SLF4J & LogBack
    - 테스트

    (3)View優先パラメータ


    1.胸腺テンプレートエンジン
    - thymeleaf 공식 사이트: https://www.thymeleaf.org/
    - 스프링 공식 튜토리얼: https://spring.io/guides/gs/serving-web-content/
    - 스프링부트 메뉴얼: https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/
    boot-features-developing-web-applications.html#boot-features-spring-mvc-template-
    engines
  • スプリングガイドThymeleaf viewNameマッピング
  • resources:templates/ +{ViewName}+ .html
    2.サンプルを使用してビューの動作を確認する

  • HelloController.java


  • Hello.html
    resources/templates/hello.html
  • <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
     <title>Hello</title>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    <p th:text="'안녕하세요. ' + ${data}" >안녕하세요. 손님</p>
    </body>
    </html>
  • index.html
    static/index.html
  • <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
     <title>Hello</title>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    Hello
    <a href="/hello">hello</a>
    </body>
    </html>
    リファレンス
  • spring-boot-devtoolsライブラリを追加すると、htmlファイルをコンパイルするだけでサーバを再起動せずにビューファイルを変更できます.
  • インテルJコンパイル方法:構築メニュー->リカバリ
  • (4)H 2データベースのインストール


    開発やテストに便利なDB、Web画面を提供

    (5)JPAとDB設定、動作確認


    1. application.yml設定
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/jpashop?serverTimezone=UTC&characterEncoding=UTF-8
        username: root
        password: root
    
      jpa:
        hibernate:
          ddl-auto: create
        properties:
          hibernate:
    #        show_sql: true
            format_sql: true
    
    logging:
      level:
        org.hibernate.SQL: debug
        org.hibernate.type: trace
    

  • spring.jpa.hibernate.ddl-auto: create
    :アプリケーションの実行時にテーブルを削除して再生成

  • show_sql
    :オプションはシステムです.HyperNateを実行するSQLをoutに残します.

  • org.hibernate.SQL
    :次のオプションがあります.
  • 2.実際の動作を確認する

  • Member.java


  • MemberRepository.java


  • MemberRepositoryTest.java
  • package com.jpabook.jpashop;
    
    import org.assertj.core.api.Assertions;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.Transactional;
    
    import static org.junit.Assert.*;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class MemberRepositoryTest {
    
        @Autowired MemberRepository memberRepository;
    
        @Test
        @Transactional
        public void testMember() throws Exception{
            //given
            Member member = new Member();
            member.setUserName("memberA");
    
            //when
            Long savedId = memberRepository.save(member);
            Member findMember = memberRepository.find(savedId);
    
            //then
            Assertions.assertThat(findMember.getId()).isEqualTo(member.getId());
            Assertions.assertThat(findMember.getUserName()).isEqualTo(member.getUserName());
            Assertions.assertThat(findMember).isEqualTo(member);
        }
    }
  • クエリー・パラメータ・ログを残す
    -> build.ライブラリをgradleに追加する
  • implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.5.6'