dany giguere
02/07/2024, 11:58 PM@Repository
class UserRepository(private val databaseClient: DatabaseClient) {
suspend fun findById(id: Long): User? =
databaseClient
.sql("SELECT * FROM user WHERE id = $id")
.map { row ->
User(
row.get("id") as Long,
row.get("username") as String,
row.get("email") as String,
null.toString()
)
}.awaitOneOrNull()
suspend fun create(username: String, email: String, password: String): User? =
databaseClient.sql("INSERT INTO user (username, email, password) VALUES ('$username', '$email', '$password')")
.map { row ->
User(
row.get("id") as Long,
row.get("username") as String,
row.get("email") as String,
null.toString()
)
}.awaitOneOrNull()
}
The way I have it the create function is not returning a User. Anyone how I could do that ? (maybe I’ll have to do another select query ???)ashmelev
02/08/2024, 12:15 AMusername
is unique in your model?dany giguere
02/08/2024, 12:35 AMRobert Jaros
02/08/2024, 7:30 AMreturnGeneratedValues
statement filter. See:
https://docs.spring.io/spring-framework/reference/data-access/r2dbc.html#r2dbc-DatabaseClient-filterRobert Jaros
02/08/2024, 7:33 AMashmelev
02/08/2024, 2:34 PMdany giguere
02/08/2024, 4:39 PMdany giguere
02/09/2024, 12:02 AM@Component
class UserMapper: BiFunction<Row, Any, User> {
override fun apply(row: Row, o: Any): User {
return User(
row.get("id") as Long,
row.get("username") as String,
row.get("email") as String,
null.toString()
)
}
}
@Repository
class UserRepository(private val databaseClient: DatabaseClient,
private val mapper: UserMapper) {
val selectUserById = """
SELECT * FROM user WHERE id = :id
"""
val insertUser = """
INSERT INTO user (username, email, password) VALUES (:username, :email, :password)
"""
suspend fun findById(id: Long): User? =
databaseClient.sql(selectUserById)
.bind("id", id)
.map(mapper::apply)
.awaitOneOrNull()
suspend fun create(user: User): User? =
databaseClient.sql(insertUser)
.filter { statement, _ -> statement.returnGeneratedValues("id").execute() }
.bind("username", user.username)
.bind("email", user.email)
.bind("password", user.password)
.fetch()
.first()
.map { user.copy(id = it["id"] as Long) }.awaitSingleOrNull()
}
Thanks @Robert Jaros and @ashmelev