Spring Data R2DBC 써보기

aosamesan·2022년 12월 8일
0

새로운 삽질을 시작해봅시다.
WebFlux에서 일반적인 JDBC를 쓰면 block때문에 쓸 수 없던 걸로 기억하는데 R2DBC라는게 있다길래 한 번 써보려고 한다.

환경

  • MacOS Ventura 13.0.1 (M1 MacMini)
  • IntelliJ IDEA Ultimate
  • JDK 17
  • Maria DB 10.3.32

디펜던시 (Spring Initializr)

  • Spring WebFlux
  • Spring Data R2DBC
  • Maria DB Driver

테이블

CREATE TABLE test.test_table (
	id INT PRIMARY KEY AUTO_INCREMENT,
    message TEXT,
    created_at DATETIME DEFAULT NOW()
)

application.yaml

spring:
	r2dbc:
    	url: r2dbc:mariadb://maria.db.server:port
        username: some_user_name
        password: some_user_password
        name: test # Database Name

entities/TestEntity.kt

@Table("test_table")
class TestEntity {
	var id: Int = 0
	var message: String? = null
	var createdAt: Timestamp? = null
}

repositories/TestRepository.kt

@Repository
interface TestRepository : R2dbcRepository<TestEntity, Int>

services/TestService.kt

@Service
class TestService(private val testRepository : TestRepository) {
	fun findAll(start: Long, display: Long): Flux<TestEntity> {
    	return testRepository
        		.findAll(Sort.by(Sort.Order.by("created_at")).descending())
                .skip(start)
                .take(display)
    }
    
    // 귀찮으니 findAll만 작성
}

config/WebConfig.kt

@Configuration
@EnableWebFlux
class WebConfig(private val testService: TestService) {
	@Bean
    fun router(): RouterFunctions<ServerResponse> {
    	return RouterFunctions.nest(
        	RequestPredicates.path("api"),
            RouterFunctions.nest(
            	RequestPredicates.path("test"),
                RouterFunctions.route(RequestPredicates.GET("")) { request ->
                	testService.findAll(
                    	request.queryParam("start").orElse("0").toLong(),
                        request.queryParam("display").orElse("10").toLong()
                    )
                    .let {
                    	ServerResponse
                        	.ok()
                            .body(BodyInserters.fromPublisher(it, TestEntity::class.java))
                    }
                }
            )
        )
    }
}

이제 test_table에 몇 개 넣어보고 /api/test를 호출해본다.

잘되네

끗.

profile
재미로 개발 하는 사람

0개의 댓글