관리 메뉴

bright jazz music

JPA 활용 + 클래스 생성 및 테이블 생성 본문

Framework/Spring

JPA 활용 + 클래스 생성 및 테이블 생성

bright jazz music 2022. 6. 9. 22:10
package org.zerok.ex2.entity;

import lombok.*;

import javax.persistence.*;

@Entity
@Table(name="tbl_memo") //name옵션이 없으면 클래스 이름으로 테이블 생성
@ToString
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Memo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long mno;

    @Column(length = 200, nullable = false)
    private String memoText;

}

/*
* @Entity
* SpringDataJPA에서는 반드시 @Entity추가가 필요.
* @Entity는 해당 클래스가 엔티티를 위한 클래스이며,
* 해당 클래스들의 인스턴스들이 JPA로 관리되는 엔티티 객체라는 것을 의미한다.
*
* @Table
* @Entity 어노테이션과 같이 사용할 수 있는 어노테이션.
* DB상에서 엔티티 클래스를 어떠한 테이블로 생성할 것인지에 대한 정보를 담기 위해 사용한다.
* 예를 들어 @Table(name="t_memo")처럼 지정하는 경우, 생성되는 테이블 이름이 't_memo'가 된다.
* 인덱스 등을 생성하는 설정도 가능하다.
*
* @Id와 @GeneratedValue
* @Entity가 붙은 클래스는 Primary Key에 해당하는 특정 필드를 @Id로 지정해야만 한다.
* @Id가 사용자가 입력하는 값을 사용하는 경우가 아니라면 자동으로 생성되는 번호를
* 사용하기 위해서 @GeneratedValue라는 어노테이션을 활용한다.
*
* @GeneratedValue(strategy = GenerationType.IDENTITY) 부분은
* PK를 자동으로 생성하고자 할 때 사용한다.(키 생성 전략이라고도 한다.)
* 만일 연결되는 DB가 오라클이면 번호를 위한 별도의 테이블을 생성하고,
* MySql이나 MariaDB면 'auto increment'를 기본으로 사용해서 새로운 레코드가
* 기록될 때마다 다른 번호를 가질 수 있도록 처리된다. 키 생성 전략은 다음과 같다
*
*   - AUTO(default) : JPA 구현체(스프링부트에서는 Hibernate)가 생성 방식을 결정
*   - IDENTITY : 사용하는 DB가 키 생성을 결정. Mysql이나 MariaDB의 경우 auto increment 방식을 이용
*   - SEQUENCE : DB의 sequence를 이용해 키를 생성. @SequenceGenerator와 같이 사용
*   - TABLE : 키 생성 전용 테이블을 생성해서 키 생성 @TableGenerator와 함께 사용
*
* @Column
* 추가적인 필드(칼럼)이 필요한 경우에 활용. @Column을 이용해서 다양한 속성을 지정 가능.
* 주로 nullable, name, length 등을 이용해서 DB의 칼럼에 필요한 정보를 제공.
* 속성 중에 columnDefinition을 이용하면 기본값을 지정할 수도 있음.
*
* @Getter
* 롬복의 @Getter를 사용하여 Getter 메서드를 생성.
*
* @Builder
* 객체를 생성할 수 있도록 처리.
* @Builder를 이용하기 위해서는 @AllArgsConstructor와 @ArgsConstructor를 항상 같이 처리해야
* 컴파일 에러가 발생하지 않는다.
*
*
*
* @Column과 반대로 DB 테이블에 칼럼으로 생성되지 않는 필드의 경우에는
* @Transient 어노테이션을 적용한다. 또한 @Column으로 기본값을 지정하기 위해서
* columnDefinition을 이용하기도 한다.
*
*   @Column(columnDefinition = "varchar(255) default 'Yes' ")
 */

 

 

#application.properties

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/bootex
spring.datasource.username=DB아이디
spring.datasource.password=DB비밀번호

#추가
spring.jpa.hibernate.ddl-auto=update     
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true


#spring.jpa.hibernate.ddl-auto:
#프로젝트 실행 시에 자동으로 DDL(create, alter, drop 등)을 생성할 것인지를 결정하는 설정.
#설정값은 create, update, create-drop, validate가 있다.
#create의 경우에는 매번 테이블 생성을 새로 시도한다. 예제서는 update를 이용하여
#변경이 필요한 경우 alter로 변경되고, 테이블이 없는 경우에는 create가 되도록 설정했다.

#spring.jpa.hibernate.format_sql:
#실제 JPA의 구현체인 Hibernate가 동작하면서 발생하는 SQL을 포맷팅해서 출력한다.
#실행되는 SQL의 가독성을 높여준다.

#spring.jpa.show-sql:
#JPA 처리 시에 발생하는 SQL을 보여줄 것인지를 결정한다

 

 


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.0)

2022-06-09 22:13:20.980  INFO 14260 --- [  restartedMain] org.zerok.ex2.Ex2Application             : Starting Ex2Application using Java 11.0.12 on DESKTOP-Q7HBM41 with PID 14260 (D:\personal\sts-personal-workspace\ex2\build\classes\java\main started by user in D:\personal\sts-personal-workspace\ex2)
2022-06-09 22:13:20.980  INFO 14260 --- [  restartedMain] org.zerok.ex2.Ex2Application             : No active profile set, falling back to 1 default profile: "default"
2022-06-09 22:13:21.019  INFO 14260 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-06-09 22:13:21.019  INFO 14260 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-06-09 22:13:21.362  INFO 14260 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-06-09 22:13:21.362  INFO 14260 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 3 ms. Found 0 JPA repository interfaces.
2022-06-09 22:13:21.671  INFO 14260 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-06-09 22:13:21.671  INFO 14260 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-06-09 22:13:21.671  INFO 14260 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-09 22:13:21.719  INFO 14260 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-06-09 22:13:21.719  INFO 14260 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 700 ms
2022-06-09 22:13:21.819  INFO 14260 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-06-09 22:13:21.835  INFO 14260 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.9.Final
2022-06-09 22:13:21.884  INFO 14260 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-06-09 22:13:21.932  INFO 14260 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-06-09 22:13:21.964  INFO 14260 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-06-09 22:13:21.964  INFO 14260 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MariaDB106Dialect
Hibernate: 
    
    create table tbl_memo (
       mno bigint not null auto_increment,
        memo_text varchar(200) not null,
        primary key (mno)
    ) engine=InnoDB
2022-06-09 22:13:22.241  INFO 14260 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-06-09 22:13:22.257  INFO 14260 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-06-09 22:13:22.273  WARN 14260 --- [  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-06-09 22:13:22.419  INFO 14260 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-06-09 22:13:22.452  INFO 14260 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-06-09 22:13:22.452  INFO 14260 --- [  restartedMain] org.zerok.ex2.Ex2Application             : Started Ex2Application in 1.658 seconds (JVM running for 2.551)

 

 

 

Comments