hibernate - 无法将类型“java.lang.String”的属性值转换为属性“user”所需的类型“server.model.User”
问题描述
我这里有点麻烦。试图为我的用户创建 10 个农场。以下是 Famplot 数据类和用户数据类:
@Entity
@IdClass(FarmPlotPK::class)
data class FarmPlot (
@Id
val slotnr: Int? = -1,
@Id
@ManyToOne
@JoinColumn(name = "username", nullable = false)
var user: User,
val plantedDate: LocalDate? = null,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "name")
var plant: Plant? = null
){}
@Entity
@Table(name="user")
data class User (
@Id
val username: String = "",
@OneToMany(mappedBy = "user")
val farmPlots: MutableSet<FarmPlot> = HashSet()
)
使用我的控制器,我尝试在 FarmPlotController 中使用此方法创建 10 个农场:
@PostMapping("/farmPlots/create/{username}")
fun createNewFarmPlot(@PathVariable(value = "username") username:String) {
val user:User = userRepository.findById(username).get()
for (i in 0..9) {
val farmPlot = FarmPlot(slotnr = i, user = user)
println(farmPlot.toString())
// Outprint is FarmPlot(slotnr=0, user=User(username=test2, farmPlots=[]), plantedDate=null, plant=null)
farmPlotRepository.save(farmPlot)
}
}
但是,当尝试向用户添加农场图时,我收到以下错误消息:
"message": "Failed to convert property value of type 'java.lang.String' to required type 'com.merchantsofrome.server.model.User' for property 'user'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.merchantsofrome.server.model.User' for property 'user': no matching editors or conversion strategy found"
FarmPlotRepository.kt
import com.merchantsofrome.server.model.FarmPlot
import com.merchantsofrome.server.model.IdClass.FarmPlotPK
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface FarmPlotRepository : JpaRepository<FarmPlot, FarmPlotPK>
FarmPlotPK.kt
@IdClass(FarmPlotPK::class)
class FarmPlotPK : Serializable {
var slotnr: Int? = -1
var user: User? = null
init{
this.slotnr=slotnr
this.user=user
}
// The override of equals, see the rules mentioned above for creating a composite primary key
override fun equals(other: Any?): Boolean {
if (other is FarmPlotPK) {
val farmPlotPK = other as FarmPlotPK?
if (this.user!!.username == farmPlotPK!!.user!!.username && this.slotnr == farmPlotPK.slotnr) {
return true
}
} else {
return false
}
return false
}
// The override of hashCode, see the rules mentioned above for creating a composite primary key
override fun hashCode(): Int {
return super.hashCode()
}
}
解决方案
使用 User.kt 中的额外构造函数对问题进行了非常简单且可能不太体面的解决方案
constructor(username: String) : this(username=username, salt = "123")
推荐阅读
- java - Appium 在 iPad 上的字段中输入文本两次
- bash - Tee 没有得到管道的输出
- asp.net-core - 在 Asp.net Core Web API 和 EF.Core 中加载相关数据的最佳实践
- terraform - 使用网络接口安全组从 AzureRM v1 迁移到 v2 时遇到问题,无法应用
- javascript - 如何在js文件中加载vue组件
- r - 在r中的特定模式之后提取字符
- json - 查询所有类型的片段
- python - 您可以将文件引用批量重新链接到 Maya 中的其他目录吗?
- kotlin - 为什么 Kotlin 类型推断不适用于功能接口?
- mongodb - 如何防止 updateOne 自动插入 { '$set': { _id: 'foobaa' } },?