들어가며
- DB 를 생성하였으니 이제 DB 에 원하는 값을 넣을 수 있어야 한다.
- 여기서는 Spring FrameWork 의 JPA Repository를 이용하여 DB 를 관리 할 것이다.
미리보기
- 실제 과제에선 다음과 같은 결과가 나왔다.
- 다음 영화 api 를 이용해 영화 데이터를 가져 오고 원하는 컬럼에 맞게 가공하여 저장 하였다.
DB 에 사용할 table 만들기
- Intellij 우측의 "Database" -> 사용할 DB 에서 우클릭 -> New -> Table 을 눌러 사용할 테이블을 생성후 이름 입력
- "columns", "keys" 등을 우클릭 하여 필요한 항목을 생성 한다.
- 만약 SQL 문이 익숙한 사람이라면 DB 를 우클릭 한 후 "Query SQL" 을 클릭해 SQL 문을 직접 써서 넘길 수 있다.
- testId 를 primary key 로 하는 table 을 하나 생성 하였다.
Entity 생성
- 우선 사용할 Table 과 동일한 구조의 data class 가 필요하다.
- 이러한 파일은 Entity 디렉토리에 저장 하기로 하였으니 Entity 디렉토리에 파일을 하나 생성 해 준다.
- 이때 "data class" 로 생성 해 주면 된다.
- 내부 코드는 다음과 같이 작성 해 준다.
- Spring 에서 제공하는 Entity 를 사용하기 위해 @Entity 를 넣어 준다.
- 사용할 Table 이름을 @Table() 안에 적어 주고
- @Column() 안에 사용할 Column 이름을 적어 주면 된다.
package com.example.runjob_blog.Entity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.Table
@Entity
@Table(name = "test")
data class test(
@Id
@Column(name = "testId")
val testId: Int = 0,
@Column(name = "testName")
val testName: String = "",
@Column(name = "testInfo")
val testInfo: String = "",
)
Repository 생성
- 이제 DB 를 관리하기 위한 Repository 를 생성 할 것이다.
- Repository 디렉토리 내부에 "Interface" 코틀린 파일을 하나 생성 해 준다.
- 내부 코드는 다음과 같이 작성 해 준다.
- 우선 위에서 작성 했던 Entity 를 import 해 준다.
- 그 후 testRepository 뒤에 : 를 붙여 return 값에 Entity 를 명시 해 준다.
package com.example.runjob_blog.Repository
import com.example.runjob_blog.Entity.test
import org.springframework.data.jpa.repository.JpaRepository
interface testRepository : JpaRepository<test, String> {
}
- JPA 를 사용하면 save, findAll, 값을 이용한 find 등 다양한 기능을 구현 없이 사용 할 수 있다.
Service 생성
- 이제 위에서 만든 Repository를 이용하여 실제로 데이터를 저장 하는 Service 를 만들어 볼 차례이다.
- 나중에 이해 하기 편하도록 정의만 해둔 "Interface" 와 실제로 구현한 "impl" 로 나누어 두었다.
- 우선 Service 디렉토리 내부에 실제 코드 구현한 파일이 들어갈 디렉토리인 "impl" 디렉토리를 생성 해 주었다.
- 그 후 "interface" 인 testService 와 "kotlin class" 인 testServiceImpl 을 생성 해 준다.
- testService.kt 파일은 다음과 같이 작성 해 준다.
- impl 이 해당 class 를 상속 받아 saveTest 를 구현 한다.
//testService.kt
package com.example.runjob_blog.Service
interface testService {
fun saveTest()
}
- testServiceImpl.kt 파일은 다음과 같이 작성 해 준다.
- 위에서 작성한 testService.kt 파일을 class testService(): 뒤에 붙여 준다.
- Entity 에서 작성한 "test" 를 test_data 변수로 생성 해 주고 data 를 넣어 test_data 를 생성 해 준다.
- 위에서 생성 했던 testRepository 의 save 기능을 이용 하여 DB 에 저장 해 준다.
//testServiceImpl.kt
package com.example.runjob_blog.Service.impl
import com.example.runjob_blog.Entity.test
import com.example.runjob_blog.Repository.testRepository
import com.example.runjob_blog.Service.testService
import org.springframework.stereotype.Service
@Service
class testServiceImpl(
val testRepository: testRepository
): testService {
override fun saveTest(){
val test_data = test(
1,
"test_name",
"test_info"
)
val res = testRepository.save(test_data)
}
}
Controller 수정과 실행
- Controller 를 다음과 같이 수정 한다.
- class 에 val testService: testService 를 추가해 방금 만들었던 testService 의 fun 인 saveTest 를 사용 가능하게 수정
- 이에 따라 testService 를 import 해야 한다.
package com.example.runjob_blog.Controller
import com.example.runjob_blog.Service.testService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/test")
class BlogTestController(
val testService: testService
) {
@GetMapping("/DBsave")
fun DBsave(){
testService.saveTest()
}
}
dependencies 수정
- 마지막으로 실제로 DB 와 연결 하기 위해선 여러 설정을 해 주어야 한다.
- 그중 첫번째가 dependencies 에 mariadb 를 추가 해 주는 것이다.
- 우선 "build.gradle.kts" 를 찾아 열어 준다.
- 그 중 "dependencies" 부분을 찾아 준다.
- 여기서 runtimeOnly가 있으면( 프로젝트를 생성 할 때 추가 했을 수 있음) 바꾸어 주고 없으면 추가 해 준다.
( runtimeOnly("org.mariadb.jdbc:mariadb-java-client") 추가 )
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-mustache")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
application.properties 추가
- resources 디렉토리 아래 application.properties 파일이 있을 것이다(없으면 생성 하면 된다)
- 이 파일을 열고 다음 코드를 붙여 넣는다.
- 이때 url 부분에는 자신의 DB ip 주소를 넣어 주고, username 과 password 부분에도 본인이 설정 한 값을 넣으면 된다.
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://192.168.0.64:3306/runjobDB
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
실행 하기
url 을 웹에서 입력 하니 원하는 값이 들어 가는 것을 알 수 있다.
'Runjob(런잡 프로젝트) > SpringBoot + Kotlin' 카테고리의 다른 글
[SpringBoot + Kotlin] Jsoup 을 이용한 웹 크롤링 (0) | 2023.04.23 |
---|---|
[SpringBoot + Kotlin] Jsoup을 이용하여 프로그램에서 API 호출 (0) | 2023.04.22 |
[SpringBoot + Kotlin] Controller 를 통해 request 보내기(실행하기) (0) | 2023.04.19 |
[SpringBoot + Kotlin] DB 생성하고 연동(Intellij 사용) (0) | 2023.04.15 |
[SpringBoot + Kotlin] 프로젝트 디렉토리 구조 (0) | 2023.04.14 |