본문 바로가기

1. Kotlin + Springboot Entity 생성하기 본문

Kotlin + SpringBoot

1. Kotlin + Springboot Entity 생성하기

00rigin 2023. 10. 1. 17:44

코프링 공부를 하기 위해 사이드 프로젝트를 시작했다.

프로젝트 생성은 다른 블로그들이 많이 생략하고...

엔티티 생성부터 시작한다.

 

프로젝트의 기본 구조는 자기 자신을 부모로 들고 있으며, 자기 자신 여러개를 자식으로 들고 있는 메모장 형태이다.

createDate와 lastModifiedDate는 모든 곳에서 기본적으로 사용할 예정이므로, BaseEntity 라는 이름의 abstact Class로 빼서 사용한다.

@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
abstract class BaseEntity {
    @CreatedDate
    @Column(nullable = false, updatable = false)
    var createdDate: LocalDateTime = LocalDateTime.now()
        protected set

    @LastModifiedDate
    @Column(nullable = false)
    var lastModifiedDate: LocalDateTime = LocalDateTime.now()
        protected set
}
@Entity
@Getter
class Memo(title: String,
           description: String) : BaseEntity(){

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private val id: Long? = null

    @Column(nullable = false)
    private var title: String = title

    @Column(nullable = false)
    private var description: String = description

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    private var parent: Memo? = null

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    @Column(name = "children_id_list")
    private var children: List<Memo>? = null
    
    
    constructor (title: String, description: String, parent: Memo) : this(title, description) {
        this.parent = parent
    }
}

children을 만든 이유는 getChildren을 사용하기 위해서 인데...

쿼리를 parent id로 하면 되니 없앨까 고민중이다.

 

기본 Entity를 만들었으니, DB를 추가한다.

일단 local에 mySql을 설치하고, localhost:3306에 peynman 이라는 schema를 생성한다.

이후 application.yml에 JPA의 기본 설정과 mysql 설정을 추가한다.

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/peynman?useSSL=false&serverTimezone=Asia/Seoul&characterEncoding=UTF-8
    username: root
    password: secured

  jpa:
    open-in-view: true
    hibernate:
      ddl-auto: create
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
      use-new-id-generator-mappings: false
    show-sql: true
    properties:
      hibernate.format_sql: true
      dialect: org.hibernate.dialect.MySQL8InnoDBDialect


logging:
  level:
    org.hibernate.SQL: debug

build.gradle.kt에도 dependencies를 추가한다.

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
	id("org.springframework.boot") version "3.1.4"
	id("io.spring.dependency-management") version "1.1.3"
	kotlin("jvm") version "1.8.22"
	kotlin("plugin.spring") version "1.8.22"
	kotlin("plugin.jpa") version "1.8.22"
	kotlin("plugin.allopen") version "1.6.21"
	kotlin("plugin.noarg") version "1.6.21"
}

group = "com.pineapple"
version = "0.0.1-SNAPSHOT"

java {
	sourceCompatibility = JavaVersion.VERSION_17
}

repositories {
	mavenCentral()
}

dependencies {
	implementation("org.springframework.boot:spring-boot-starter-data-jpa")
	implementation("org.springframework.boot:spring-boot-starter-web")
	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
	implementation("org.jetbrains.kotlin:kotlin-reflect")
	implementation("org.projectlombok:lombok:1.18.22")
	runtimeOnly("com.mysql:mysql-connector-j")
	testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.withType<KotlinCompile> {
	kotlinOptions {
		freeCompilerArgs += "-Xjsr305=strict"
		jvmTarget = "17"
	}
}

tasks.withType<Test> {
	useJUnitPlatform()
}

실행하면 아래와 같이 JPA를 통해 DB에 테이블이 생성된다.

오늘 배운것!

1. kotlin은 optional 대신 nullable한 값을 표현할 때 "?" 를 사용한다.

- var: Long? = null 과 같다.

2. kotlin class는 기본 생성자를 클래스의 () 안에서 지원한다. 이 외에 사용하고 싶은 경우 다른 생성자를 클래스 내부에 만들 수 있다.

3. var val 을 통해 변수와 상수를 구분한다. java에서 final이 val과 같은 느낌인 것 같다.

 

 

Comments