Martin Wangen
Martin Wangen

Reputation: 37

Composite-id class must implement Serializable

I'm trying to user JPA with kotlin and basicly got two classes, who should work together. I am having a problem with how I to make data class Crops serializable. I've tried adding @Serializable to Crops, but IntelliJ tells me Crops dont have a constructor. Here are the two classes:

@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()

All help is appriciated! Thanks :)

Upvotes: 0

Views: 11452

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36223

You must create a IdClass for Crops because JPA requires to have a single class for methods like EntityManager.find()

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

Then use it with @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
}}

Upvotes: 3

Related Questions