【问题标题】:Composite-id class must implement SerializableComposite-id 类必须实现 Serializable
【发布时间】:2019-06-30 08:57:04
【问题描述】:

我正在尝试将 JPA 与 kotlin 一起使用,并且基本上有两个类,它们应该一起工作。我在如何使数据类 Crops 可序列化时遇到问题。我尝试将 @Serializable 添加到 Crops,但 IntelliJ 告诉我 Crops 没有构造函数。这是两个类:

@Entity
data class Crops(
    val amountOwned: Int = 0
) {

@Id
@ManyToOne(fetch = FetchType.EAGER)
lateinit var user: User


@ManyToOne(fetch = FetchType.EAGER)
lateinit var plant: Plant


constructor(user: User, plant: Plant) : this() {
    this.plant = plant
    this.user = user
}}


@Entity
data class User (
    @Id
    val username: String = "",

    @get: NotBlank
    val password: String = "",

    @get: NotBlank
    val salt: String = "",

    @OneToMany(mappedBy = "user")
    val crops: MutableSet<Crops> = HashSet()

感谢所有帮助!谢谢:)

【问题讨论】:

  • 您可以尝试在 Crops 类中使用 MapsId 代替 Id 吗?
  • @SimonMartinelly 谢谢,但得到 AnnotationException: No identifier specified for entity
  • 作为临时解决方案,我添加了@Id val id: Int.
  • 我会说你需要一个用于作物的 IdClass。就像你有一个复合键一样。你试过吗?
  • IdClass 工作!谢谢!

标签: hibernate spring-boot jpa kotlin


【解决方案1】:

您必须为 Crops 创建一个 IdClass,因为 JPA 需要为 EntityManager.find() 等方法提供一个类

data class CropsId (val username: String = "")

然后将它与@IdClass 一起使用

@IdClass(CropsPK::class)
@Entity
data class Crops(
    val amountOwned: Int = 0
) {

@Id
@ManyToOne(fetch = FetchType.EAGER)
lateinit var user: User


@ManyToOne(fetch = FetchType.EAGER)
lateinit var plant: Plant


constructor(user: User, plant: Plant) : this() {
    this.plant = plant
    this.user = user
}}

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 2011-10-26
    • 2013-11-05
    • 1970-01-01
    • 2013-10-19
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多