MySQL & JPA SpringBoot 연동 및 테스트(Gradle)

mingki·2022년 1월 25일
0

SpringBoot & JPA

목록 보기
9/26
post-thumbnail

📚 공부한 책 : 코드로배우는 스프링 부트 웹프로젝트

1. 프로젝트 의존성 추가

  • build.gradle 에 의존성을 추가한다

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // JPA
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'mysql:mysql-connector-java' // MySql
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

2. application.properties에 DB 정보를 추가한다

// MySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
// DB Source URL
spring.datasource.url=jdbc:mysql://localhost:3306/bootex
// DB username
spring.datasource.username=BOOTUSER
// DB password
spring.datasource.password=1234
// 처리시 발생하는 SQL을 보여줄 것인지 결정
spring.jpa.show-sql=true
// 프로젝트 실행시 자동으로 DDL(create, alter, drop) 을 생성할 것 인지 결정하는 설정
// create : 매번 테이블 생성을 새로 시도한다 / update : 변경이 필요한 경우 alter로 변경되고 테이블이 없는경우 create가 된다
spring.jpa.hibernate.ddl-auto=update
// 실제 JPA 구현체인 Hibernate가 동작하면서 발생하는 SQL을 포맷팅해서 출력한다 -> 실행되는 SQL의 가독성을 높여준다
spring.jpa.properties.hibernate.format_sql=true

3.엔티티(Entity) 생성하기

import lombok.*;
import javax.persistence.*;

@Entity 
-> // 해당 클래스의 인스턴스들이 JPA로 관리되는 엔티티 객체라는 것을 의미한다 / 해당 어노테이션이 붙은 클래스는 오셥에 따라 자동으로 테이블 생성이 가능하고 클래스의 멤버 변수에 따라 자동으로 컬럼들도 생성된다

@Table(name = "tbl_memo") 
-> // @Entity 어노테이션과 같이 사용할 수 있는 어노테이션 -> DB상에서 엔티티 클래스를 어떤 테이블로 생성할 것인지에 대한 정보를 담기위함

@Data

@Builder
@AllArgsConstructor // @Builder 를 이용하기 위해서 항상 같이 처리해야 컴파일 에러가 발생하지 않는다
@NoArgsConstructor // @Builder 를 이용하기 위해서 항상 같이 처리해야 컴파일 에러가 발생하지 않는다
public class Memo {

   @Id // @Entity 가 붙은 클래스는 PK에 해당하는 특정필드를 @Id로 지정해야 한다
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   -> // 해당 어노테이션은 사용자가 입력하는 값을 사용하는 경우가 아니면 자동으로 생성되는 번호를 사용하기 위해 사용한다
   private Long mno;
   
   @Column 
   -> // 추가적인 필드(컬럼)이 팔요한 경우 사용 * DB 테이블에는 컬럼으로 생성되지 않는 필드의 경우 @Transient를 사용한다
   private String memoText;
}

4.프로젝트 실행

Hibernate: 
    create table tbl_memo (
       mno bigint not null auto_increment,
        memo_text varchar(255),
        primary key (mno)
    ) engine=InnoDB```
    
    위와 같이 테이블 생성에 필요한 SQL을 확인 할 수 있다    
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.3)

2022-01-25 21:58:32.931  INFO 93611 --- [  restartedMain] com.example.ex2.Ex2Application           : Starting Ex2Application using Java 11.0.13 on Minjiui-MacBookAir.local with PID 93611 (/Volumes/ming/git/LearnFromCode/ex2/out/production/classes started by minjipark in /Volumes/ming/git/LearnFromCode/ex2)
2022-01-25 21:58:32.933  INFO 93611 --- [  restartedMain] com.example.ex2.Ex2Application           : No active profile set, falling back to default profiles: default
2022-01-25 21:58:33.149  INFO 93611 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-25 21:58:33.153  INFO 93611 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-25 21:58:34.371  INFO 93611 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-01-25 21:58:34.410  INFO 93611 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 28 ms. Found 0 JPA repository interfaces.
2022-01-25 21:58:35.447  INFO 93611 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-01-25 21:58:35.461  INFO 93611 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-01-25 21:58:35.461  INFO 93611 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-25 21:58:35.620  INFO 93611 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-01-25 21:58:35.621  INFO 93611 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2467 ms
2022-01-25 21:58:36.066  INFO 93611 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-01-25 21:58:36.108  INFO 93611 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.4.Final
2022-01-25 21:58:36.279  INFO 93611 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-01-25 21:58:36.369  INFO 93611 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-01-25 21:58:36.830  INFO 93611 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-01-25 21:58:36.855  INFO 93611 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect

Hibernate: 
    create table tbl_memo (
       mno bigint not null auto_increment,
        memo_text varchar(255),
        primary key (mno)
    ) engine=InnoDB
    
2022-01-25 21:58:37.581  INFO 93611 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-01-25 21:58:37.587  INFO 93611 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-01-25 21:58:37.699  WARN 93611 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-01-25 21:58:38.483  INFO 93611 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-01-25 21:58:38.533  INFO 93611 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-25 21:58:38.547  INFO 93611 --- [  restartedMain] com.example.ex2.Ex2Application           : Started Ex2Application in 6.54 seconds (JVM running for 7.695)

5.테이블 생성확인

-> Memo클래스에서 지정한 tbl_memo 이름을 가지고 mno , memoText 두 컬럼을 가진 테이블이 생성된다

profile
비전공초보개발자

0개의 댓글