hibernated icon indicating copy to clipboard operation
hibernated copied to clipboard

Support for Composite Primary Keys with @EmbeddedId

Open vnayar opened this issue 4 months ago • 1 comments

Is it currently possible to have a multi-column primary key?

For example, imagine a table of passports, and each person can actually get several passports over the course of their life. Thus, the unique primary key for a passport might be (PassportId, IssueDate).

With Hibernate, this is often accomplished using an @Embeddable class, but annotating it with @EmbeddedId rather than just @Id.

https://www.baeldung.com/spring-jpa-embedded-method-parameters

A workaround to this problem (if one can add an additional column), is to make a string column that combines multiple other columns, and compute this column as a D @property, e.g.

class Passport {
  @Id
  @property string id() {
    return passportId ~ "::" ~ issueDate;
  }

  @Id
  @property void id(string id) {
    import std.string : split;
    string[] parts = id.split("::");
    enforce(parts.length == 2, "Invalid Passport.id value: " ~ id);
    this.passportId = parts[0];
    this.issueDate = parts[1];
  }

  string passportId;
  string issueDate;
}

vnayar avatar Feb 28 '24 11:02 vnayar