【发布时间】:2020-07-03 01:58:46
【问题描述】:
我对 String Boot 和后端开发(可能三天或更短时间)非常陌生,我希望构建 REST API 以从不同的客户端使用。
所以我从一个简单的演示应用开始,它有一个名为/register 的端点。我们发布一个带有username 和password 的JSON 字符串以创建一个新用户(如果不存在)。
我将JPA 与HSQLDB 一起使用,它在内存上运行良好。但是最近我想用RxJava,因为我熟悉Android,所以我切换到R2DBC和MySQL。
MySQL 服务器在端口 3306 上运行良好,并且该应用已在 localhost:8080 上使用 PostMan 进行了测试
当我尝试查询用户表或插入实体时出现问题,它看起来像这样:
{
"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"
}
这是异常的完整 logfile。
我一直在寻找解决方案几个小时,但我似乎在任何地方都找不到它,所以我希望我能在这里找到它。
让我们分解项目以便更容易找到解决方案:
1.数据库:
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。数据库配置:
@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.注册控制器:
@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.用户服务:
@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.最后,这是我的 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 和 RegistrationRequest 只是带有用户名和密码的简单对象。
我错过了什么?
如果您需要更多代码,请发表评论。
【问题讨论】:
-
你手动创建了user_entity表吗?
-
@shazin 是的,正如您在第一个屏幕截图中看到的那样,我使用 IntelliJ 控制台来执行此操作,它会在 MySQL Workbench 和 Terminal 中做出反应。
标签: java mysql spring spring-boot kotlin