0

I need to define an Entity identified by a composite key, and this composite key shall be generated automatically. Here is the composite key...

@AllArgsConstructor
@NoArgsConstructor
public class PK implements Serializable {

    private UUID id;
    private int version;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PK pk = (PK) o;
        return Objects.equals(id, pk.id) && Objects.equals(version, pk.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, version);
    }
}

... end here the entity:

@Getter
@Entity
@Table(name = "questionnaire")
@IdClass(PK.class)
public class Questionnaire {

    @Id
    @GeneratedValue
    @NotNull
    @Column(name = "id", nullable = false, updatable = false)
    private UUID id;

    @Id
    @GeneratedValue(strategy= GenerationType.SEQUENCE)
    @Column(name = "version", nullable = false, updatable = false)
    @NotNull
    private int version;

    @Column(name = "definition")
    @Lob
    @Setter
    private String definition;
}

The composite key consists of fields id and version, where id shall contain an auto-generated UUID whereas version shall be an auto-incremented integer. The problem is that version shall start from 1 for every new entity:

+--------------------------------------+---------+------------+
|                                   ID | VERSION | DEFINITION |
+--------------------------------------+---------+------------+
| 250d7ef2-fb84-4a61-9ad4-bff3d2fa8db7 |       1 | {CLOB}     |
| 250d7ef2-fb84-4a61-9ad4-bff3d2fa8db7 |       2 | {CLOB}     |
| 250d7ef2-fb84-4a61-9ad4-bff3d2fa8db7 |       3 | {CLOB}     |
| 7102cf45-1e4b-4e3f-b8e9-ab90dd597f21 |       1 | {CLOB}     |
| 7102cf45-1e4b-4e3f-b8e9-ab90dd597f21 |       2 | {CLOB}     |
| 7102cf45-1e4b-4e3f-b8e9-ab90dd597f21 |       3 | {CLOB}     |
+--------------------------------------+---------+------------+

In the table above, there are 2 entities (250d7ef2-fb84-4a61-9ad4-bff3d2fa8db7 and 7102cf45-1e4b-4e3f-b8e9-ab90dd597f21), each with 3 versions.

Any help would be really appreciated.

j3d
  • 9,492
  • 22
  • 88
  • 172
  • Possible duplicate of https://stackoverflow.com/questions/53595226/how-to-autoincrement-an-id-in-a-composite-primary-key-in-hibernate – Varun Jain Feb 11 '20 at 15:04
  • No... in the answer provided they are setting the second field in the key manually... – j3d Feb 11 '20 at 15:19

0 Answers0