Categories
java kotlin mysql spring spring-boot

Spring Boot R2DBC with MySQL – Exception: Table not found

I’m extremely new to String Boot and backend development (maybe three days or less) and I have the desire to build REST API to consume from different clients.

So I started by a simple demo app that has an endpoint called /register. We post a JSON string with username and password to create a new user if not exist.

I was using JPA with HSQLDB and it worked fine persisting on memory. But recently I wanted to use RxJava since I’m familiar with on Android, so I switched to R2DBC with MySQL.

MySQL server is running fine on port 3306 and the app was tested using PostMan on localhost:8080

The problem occurs when I try to query users table or insert entities and it looks like this:

{
"timestamp": "2020-03-22T11:54:43.466+0000",
"status": 500,
"error": "Internal Server Error",
"message": "execute; bad SQL grammar [UPDATE user_entity SET username = $1, password = $2 WHERE user_entity.id = $3]; nested exception is io.r2dbc.spi.R2dbcBadGrammarException: [42102] [42S02] Table \"USER_ENTITY\" not found; SQL statement:\nUPDATE user_entity SET username = $1, password = $2 WHERE user_entity.id = $3 [42102-200]",
"path": "/register"
}

Here’s the full logfile for the exception.

I Have been looking for a solution for hours and I seem like not finding it anywhere, so I hope that I will find it here.

Let’s break down the project so it’s easier to find the solution:

1. database:

enter image description here

2. application.properties:

logging.level.org.springframework.data.r2dbc=DEBUG
spring.datasource.url=jdbc:mysql://localhost:3306/demodb
spring.datasource.username=root
spring.datasource.password=root

3. DatabaseConfiguration:

@Configuration
@EnableR2dbcRepositories
class DatabaseConfiguration : AbstractR2dbcConfiguration() {
override fun connectionFactory(): ConnectionFactory
= ConnectionFactories.get(
builder().option(DRIVER, "mysql")
.option(HOST, "localhost")
.option(USER, "root")
.option(PASSWORD, "root")
.option(DATABASE, "demodb")
.build()
)
}

4. RegistrationController:

@RequestMapping("/register")
@RestController
class RegistrationController @Autowired constructor(private val userService: UserService) {
@PostMapping
fun login(@RequestBody registrationRequest: RegistrationRequest): Single<ResponseEntity<String>>
= userService.userExists(registrationRequest.username)
.flatMap { exists -> handleUserExistance(exists, registrationRequest) }

private fun handleUserExistance(exists: Boolean, registrationRequest: RegistrationRequest): Single<ResponseEntity<String>>
= if (exists) Single.just(ResponseEntity("Username already exists. Please try an other one", HttpStatus.CONFLICT))
else userService.insert(User(registrationRequest.username, registrationRequest.password)).map { user ->
ResponseEntity("User was successfully created with the id: ${user.id}", HttpStatus.CREATED)
}

}

5. UserService:

@Service
class UserService @Autowired constructor(override val repository: IRxUserRepository) : RxSimpleService<User, UserEntity>(repository) {
override val converter: EntityConverter<User, UserEntity> = UserEntity.Converter
fun userExists(username: String): Single<Boolean>
= repository.existsByUsername(username)
}

6. RxSimpleService:

abstract class RxSimpleService<T, E>(protected open val repository: RxJava2CrudRepository<E, Long>)  {
protected abstract val converter: EntityConverter<T, E>
open fun insert(model: T): Single<T>
= repository.save(converter.fromModel(model))
.map(converter::toModel)
open fun get(id: Long): Maybe<T>
= repository.findById(id)
.map(converter::toModel)
open fun getAll(): Single<ArrayList<T>>
= repository.findAll()
.toList()
.map(converter::toModels)
open fun delete(model: T): Completable
= repository.delete(converter.fromModel(model))
}

7. RxUserRepository:

@Repository
interface IRxUserRepository : RxJava2CrudRepository<UserEntity, Long> {
@Query("SELECT CASE WHEN EXISTS ( SELECT * FROM ${UserEntity.TABLE_NAME} WHERE username = :username) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END")
fun existsByUsername(username: String): Single<Boolean>
}

8. And finally, here’s my UserEntity

@Table(TABLE_NAME)
data class UserEntity(
@Id
val id: Long,
val username: String,
val password: String
) {
companion object {
const val TABLE_NAME = "user_entity"
}
object Converter : EntityConverter<User, UserEntity> {
override fun fromModel(model: User): UserEntity
= with(model) { UserEntity(id, username, password) }
override fun toModel(entity: UserEntity): User
= with(entity) { User(id, username, password) }
}
}

User and RegistrationRequest are just simple objects with username and password.
What I have missed?
Please leave a comment if you need more code.