MySQL에 있는 json타입을 JPA로 다루어 보는 방법을 정리해보도록 하겠습니다
MySQL json reference
https://dev.mysql.com/doc/refman/8.0/en/json.html
dependencies {
...
// JSON in MySQL
implementation("com.vladmihalcea:hibernate-types-52:2.16.2")
}
도메인 설계는 작가 & 책 으로 이루어져있으며, 이 중 책은 실제 도메인이 아니고 json타입으로 들어가는 객체입니다
Book.kt
data class Book(
var id: String = automaticNumbering(),
val title: String,
val price: Int,
)
Author.kt
@Entity
@TypeDef(name = "json", typeClass = JsonType::class)
class Author(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private val id: Long? = null,
private val name: String,
private val gender: Gender,
private val age: Int,
@Type(type = "json")
@Column(columnDefinition = "json")
private var books: List<Book>
)
그러면 진짜 간단하게 설정이 완료됩니다
AuthorDto.kt
data class AuthorDto(
val id: Long?,
val name: String,
val gender: Gender,
val age: Int,
val books: List<BookDto>
)
Repository.kt
interface AuthorRepository : JpaRepository<Author, Long> {
}
AuthorService.kt
@Service
class AuthorService(private val authorRepository: AuthorRepository) {
override fun findAuthors(): List<AuthorDTO> {
val findAuthors = authorRepository.findAll()
return findAuthors.map { author -> author.toAuthorDto() }
}
@Transactional
override fun registerAuthor(requestDTO: AuthorDTO): AuthorDTO {
val saveAuthor = authorRepository.save(requestDTO.toEntity())
return saveAuthor.toAuthorDto()
}
...
}
AuthorControllere.kt
@RestController
class AuthorController(private val authorService: AuthorService) {
@GetMapping(value = ["/authors"], produces = ["application/json"])
fun findAuthors(): Success<List<AuthorDTO>> {
val findAuthors = authorService.findAuthors()
return Success(findAuthors, "작가 & 책 목록들입니다.")
}
@PostMapping(value = ["/author"], produces = ["application/json"])
fun registerAuthor(@RequestBody requestDTO: AuthorDTO): Success<AuthorDTO> {
val saveAuthor = authorService.registerAuthor(requestDTO)
return Success(saveAuthor, "저장이 완료되었습니다.")
}
...
}
postman
reuqest / response
끗! 읽어주셔서 감사합니다 (꾸벅)
좌충우돌 kotlin spring boot project 생성기 https://github.com/HongChaeMin/kotlin/tree/main/kotlinServer