首页 > 解决方案 > 无法将类型“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()
    }

}

标签: hibernatespring-bootmodel-view-controllerkotlinspring-data-jpa

解决方案


使用 User.kt 中的额外构造函数对问题进行了非常简单且可能不太体面的解决方案

constructor(username: String) : this(username=username, salt = "123")

推荐阅读