Pergunta

On every request to my SessionBean I need to receive the last added instance of a JPA entity whose PK is declared with @Id @GeneratedValue(strategy=GenerationType.AUTO) Long id.

My current approach is to add ORDER BY e.id DESC to the query. Unfortunately im not sure whether generated ids are strictly increasing for subsequently persisted entities and I can't seem to find any documentation on that topic. Can anyone help me with that?

Foi útil?

Solução

JPA does not specify the order of id generation, so the provider is free to issue nonsequential ids.

If you want to rely on the entity insertion order, consider adding a temporal createdAt or modifiedAt field to your entity. This approach is used by some persistace frameworks, e.g. ActiveRecord.

You can leave the generation of this value to the provider by using a callback in a base entity class:

@PrePersist
void makeCreationTimestamp() {
 createdAt = System.currentTimeMillis();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top