Search code examples
javaspringhibernatejpaspring-data-jpa

Can I tell Spring Data JPA/Hibernate order of composite Primary Key?


I am using Spring Data JPA with hbm2ddl.auto=update. I defined have an entity with composite primary key (using @EmbeddedId). Is it possible for me to define the order of the composite key when the table is being created? That is, it whether it be (userid, token) or (token, userid).


Solution

  • Hibernate will generate the DDL script using the entity property order. While you can override the embeddable column names, you can't specify the column order.

    Because the @EmbeddedId will generate a composite primary key, an index will automatically be generated anyway. You just have to make sure your SELECT statements ORDER BY clauses use the same column sequence as the composite id, to make the indexing resolving as efficient as possible.