如标题中所述,我无法在我的 Postgres 数据库中插入或更新记录。我刚开始使用 spring 和 kotlin,所以可能缺少一些非常基本的配置。提前致谢
这是我的代码库
用户存储库
@Repository
interface UserRepository : ReactiveCrudRepository<User, Int> {}
用户模型 @Table("user_app")
data class User (
@Id
@Column("id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
val id : Int? = null,
@Column("username")
val username : String?,
@Column("email")
val email : String?,
@Column("name")
val name : String?,
@Column("password")
val password : String?
)
用户 控制器@组件
class UserController{
@Autowired
private lateinit var userRepository : UserRepository
fun getAllUsers() : Flux<User> = userRepository.findAll()
fun getUserById( userId: Int) : Mono<User> = userRepository.findById(userId)
fun createUser(user: User): Mono<User> = userRepository.save(user)
fun updateUser(user: User) : Mono<User> = userRepository.save(user)
}
用户配置
@Configuration
class UserConfiguration {
@FlowPreview
@Bean
fun userRouter(controller: UserController): RouterFunction<ServerResponse> = router{
("/users").nest{
GET("") { _ ->
ServerResponse.ok().body(controller.getAllUsers())
}
GET("/{id}") { req ->
ServerResponse.ok().body(controller.getUserById(req.pathVariable("id").toInt()))
}
accept(MediaType.APPLICATION_JSON)
POST("") {req ->
ServerResponse.ok().body(req.bodyToMono(User::class.java).doOnNext { user ->
controller.createUser(user) })
}
accept(MediaType.APPLICATION_JSON)
PUT("") {req ->
ServerResponse.ok().body(req.bodyToMono(User::class.java).doOnNext { user ->
run {
controller.updateUser(user)
}
})
}
}
}
}
R2dbc配置
@Configuration
@EnableR2dbcRepositories
class R2dbcConfiguration : AbstractR2dbcConfiguration() {
@Bean
override fun connectionFactory(): PostgresqlConnectionFactory {
val config = PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.database("postgres")
.username("postgres")
.password("pass123")
.build()
return PostgresqlConnectionFactory(config)
}
}