Kotlin JPA id fo composite key
Kotlin JPA id fo composite key
Composite keys in Kotlin JPA have a few specific requirements that aren’t obvious from the documentation. The class must implement Serializable (Hibernate requires it), and serialVersionUID needs to be set explicitly. The @Id annotation goes on each field that’s part of the composite key — not on a separate @EmbeddedId class in this approach.
- Sample Table
1
2
3
4
5
Create table DataTable(
MainID number(19),
SecondaryId number(19),
TernaryId varchar2(20)
);
- Add composite key to the table
1
create unique index DataTable_idx on DataTable (MainID, SecondaryId, TernaryId);
- Kotlin code for composite key
@id is added to all the composite key fields
Serializable is added as it is required by kotlin
serialVersionUID is added as it is required by hibernate
1
2
3
4
5
6
7
8
9
10
@Entity
@Table(name = "DataTable")
class DataIDLinks(
@Id@Column(name = "MainID", nullable = false) val mainID: Long,
@Id@Column(name = "SecondaryId", nullable = false) val secondaryId: Long,
@Id @Column(name = "TernaryId", nullable = true) val ternaryId: String ) : Serializable{
companion object {
private const val serialVersionUID: Long = 170010121L
}
}
This post is licensed under
CC BY 4.0
by the author.