Skip to content

Instantly share code, notes, and snippets.

@mchlstckl
Last active August 4, 2023 07:37
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchlstckl/4f9602b5d776878f48f0 to your computer and use it in GitHub Desktop.
Save mchlstckl/4f9602b5d776878f48f0 to your computer and use it in GitHub Desktop.
Example entity with composite key Spring Boot and Kotlin
// This will not serialize!
data class Muppet(val name: String)
// This will serialize!
data class Puppet(val name: String = "")
// Composite key class must implement Serializable
// and have defaults.
class PropertyId(
val uuid: UUID = UUID.randomUUID(),
val name: String = "") : Serializable
// Need defaults everywhere!
@Entity
@IdClass(PropertyId::class)
data class Property(
@Id val uuid: UUID = UUID.randomUUID(),
@Id val name: String = "",
val value: String = "")
@johnacliffe
Copy link

Thank you, this was very helpful. Glad I found dug to the 2nd page of google and found this.

@binakot
Copy link

binakot commented Jul 31, 2019

Works like a charm 🍸
Thank you :octocat:

@ralf-br
Copy link

ralf-br commented Dec 12, 2019

I almost did set all those awful default values like in your example - but then I found the official Kotlin Docs recommending the JPA compiler plugin which generates the no-arg constructors for you! I think THAT is the way to go and worked perfectly fine for me: https://kotlinlang.org/docs/reference/compiler-plugins.html#jpa-support

@rratliff
Copy link

rratliff commented Dec 3, 2020

To add to what @Mineralf said, the Kotlin JPA plugin needs a small hint to create that no-arg constructor. I found that I needed to add @Embeddable to the data class to get it to work.

@Embeddable
data class PropertyId(
        val uuid: UUID,
        val name: String) : Serializable

@joergi
Copy link

joergi commented Jun 30, 2021

To add to what @Mineralf said, the Kotlin JPA plugin needs a small hint to create that no-arg constructor. I found that I needed to add @Embeddable to the data class to get it to work.

@Embeddable
data class PropertyId(
        val uuid: UUID,
        val name: String) : Serializable

Thanks a lot this was solving our problems!

@valerymarkov
Copy link

Thanks a lot for pointing to @IdClass and @Id annotations!
I tried using @EmbeddedId first and couldn't get rid of "org.springframework.orm.jpa.JpaSystemException: Could not set field value [] value by reflection : " error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment