NodeJS에서 Spring 전환하기 3

장달진·2024년 4월 22일

JPA 사용해보기

Coffee Entity

@Entity
data class Coffee(
    @Id
    val id: String,
    val name: String
) {
    constructor(name: String) : this(UUID.randomUUID().toString(), name)
}

Coffee Repository

interface CoffeeRepository : CrudRepository<Coffee , String>

Coffee Controller

@RestController
@RequestMapping("/coffee")
class CoffeeController(private val coffeeRepository: CoffeeRepository) {

    init {
        coffeeRepository.saveAll(
            listOf(
                Coffee("Coffee1"),
                Coffee("Coffee2"),
                Coffee("Coffee3"),
                Coffee("Coffee4")
            )
        )
    }

    @GetMapping
    fun getCoffeeList(): ResponseEntity<List<Coffee>> {
        return ResponseEntity(coffeeRepository.findAll().toList(), HttpStatus.OK)
    }

    @GetMapping("/{id}")
    fun getCoffeeById(@PathVariable id: String): ResponseEntity<Coffee> {
        return ResponseEntity(coffeeRepository.findById(id).orElseThrow(), HttpStatus.OK)
    }

    @PostMapping
    fun postCoffee(@RequestBody coffee: Coffee): ResponseEntity<Coffee> {
        return ResponseEntity(coffeeRepository.save(coffee), HttpStatus.CREATED)
    }

    @PutMapping("/{id}")
    fun putCoffee(@PathVariable id: String, @RequestBody coffee: Coffee): ResponseEntity<Coffee> {
        return ResponseEntity(
            coffeeRepository.save(coffee), if (coffeeRepository.existsById(id))
                HttpStatus.OK
            else
                HttpStatus.CREATED
        )
    }

    @DeleteMapping("/{id}")
    fun deleteCoffee(@PathVariable id: String): Unit {
        coffeeRepository.deleteById(id)
    }
}

@Entity

@Entity@Id한개 붙인다고 선언이 끝났다. 외래키 경우 @ManyToOne 같은 것을 사용하는 것으로 봐선 NodeJS의 TypeORM과 굉장히 유사하다.

CrudRepository<T , ID>

CrudRepository만 구현하도록 달아 놓고 Controller에 넣으니까 IoC가 알아서 해주더라. 뭐야 충격 그 잡채. 왜 알아서 만들어주는 걸까. NodeJS에서는 TypeORM BaseRepository 사라지고 Prisma로 옮겨간 후에 BaseRepository 다 만들어서 구현했는데 스프링 너란 자식. 좀 좋다?

application.properties

NodeJS로 보면 .env와 같은 친구이다. application.yml로 사용도 가능 한 것 같은데 아직은 기본 형태로 사용하려고 한다. 당장 나의 눈에는 yml이 더 편해보이고 좋아보인다.

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost/<database>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto 이녀석 부터 살펴보자면 update로 해두면 Prisma의 migrate dev를 자동으로 해준다. 대단한것(?) 좀 편하네. 물론 dev 환경일때나 사용하지 release 환경에서는 none으로 하겠지만 맘에 든다!

spring.datasource는 기본적으로 설정해줘야 하는 것이고 멀티데이터베이스 찾아보니까 방법은 존재한다. Prisma 사용할 때는 내가 다 알아보느라고 고생했는데 역시 스프링 개발자가 많으니까 행복하다

[오늘의 총평]
너무 편하다. 이상하게 편하다. 난 여태 불편함에 찌들어 있었던 것 같기도하다.

profile
아무것도 모르는 개발자

0개의 댓글