【问题标题】:Is it possible to dynamically set the schema in Spring Repository @Query annotation?是否可以在 Spring Repository @Query 注释中动态设置模式?
【发布时间】:2019-11-30 19:22:09
【问题描述】:

我有一个现有的数据库,可以将团队分成单独的模式,其中具有相同的表结构(丑陋,我知道)。我需要接受团队名称作为获取请求中的参数,并动态查询该数据的适当架构。

我已尝试使用查询参数设置架构以防止 SQL 注入,但我了解到您不允许使用这些设置架构/表。

我创建了这个代码设置示例:

Entity:

@Entity
@Immutable
data class UserEntity (
   @Id
   @Column(name = "userId")
   var userId: String,

   @Column(name = "phone")
   var phone: String
)

-------------------

Controller:

@GetMapping("/getPhoneFromCorrectSchema"
fun getPhoneFromCorrectSchema(
   @RequestParam(value = "userId") userId: String,
   @RequestParam(value = "teamName") teamName: String
) : String {
   return userRepo.getPhoneFromCorrectSchema(use( rId, teamName)
}

---------------------
Repository:

iterface UserRepo : CrudRepository<UserEntity, String> {
 @Query(nativeQuery = true,
        value = "SELECT * FROM :teamName.USER_TABLE WHERE userId = :userId"
 )
 fun getPhoneFromCorrectSchema(@Param("userId") userId: String, @Param("teamName") teamName: String) : UserEntity
}

【问题讨论】:

    标签: java spring spring-boot jpa kotlin


    【解决方案1】:

    它看起来很丑,我没有任何明确的解决方案,但我可以告诉你,如果你使用 :teamName.USER_TABLE 它不会尝试解析“teamName”,它会尝试解析“teamName.USER_TABLE”。您可以尝试将 teamName 和 tableName 作为单个参数传递,而不是仅传递 teamName 并附加“.TableName”。它可能会起作用。

    【讨论】:

    • 感谢您的回复,但这似乎不起作用
    猜你喜欢
    • 2020-11-28
    • 2014-05-21
    • 2022-01-19
    • 1970-01-01
    • 2016-03-31
    • 2021-07-04
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多