3

This question is about ordering inside a composed index, which is a more specific problem than ordering columns inside a table.

I have a simple class with a composed id:

@Embeddable
class PrimaryKeyClass {
    private int a;
    private int b;
}

@Entity
class SimpleClassWithComposedId {
    @EmbeddedId
    PrimaryKeyClass id;
}

It seems like hibernate is generating the primary key with the fields ordered by lexicographical order, at least it was what happened in my tests cases. But i would like to know if there is a way to specify the order of the fields in the primary key, because this is very important since we can heavily optmize queries that use a prefix of the composed index ( i have read this in the postgres docs )

krionz
  • 417
  • 1
  • 4
  • 15

1 Answers1

1

One option would be to rename the columns in the table in the lexical order.

Alternatively, does adding a Column name help?

@Column(name = "a")
private int k_2a;

@Column(name = "b")
private int k_1a;
Thiyanesh
  • 2,360
  • 1
  • 4
  • 11
  • 1
    I have done some more testing, and what happened is that hibernate takes into consideration the field name not the name inside the @Column. This is sad. – krionz Feb 11 '21 at 14:13
  • @krionz, Oh ok. So, changing the table column names seems to be the only possible option.(need to take care of any other existing clients reading directly from table) – Thiyanesh Feb 11 '21 at 17:07
  • @krionz, one last suggestion, have you tried adding the java class attributes in different order along with name change and @Column annotation. Something like ```@Column(name = "b") private int k_1a; @Column(name = "a") private int k_2a; ``` Not sure whether this will work, please give it a try, if you haven't already. Do update when you found a working solution without updating the table column names. Thank you and all the best – Thiyanesh Feb 11 '21 at 19:14
  • 1
    Yes, it works because of the nane change, but not because of the order of the attributes inside the class or names inside @Column annotation. I think i will change the name of the entity properties. Thank you. – krionz Feb 12 '21 at 14:11
  • @krionz, thank you for sharing the result. – Thiyanesh Feb 12 '21 at 17:18