Ruben Garat
Ruben Garat

Reputation: 21

Create a Sequence using JPA2 backed by hibernate

I need to be able to get a sequential number (I don't mind if there are holes in the generation) and I think a SQL Sequence would be the perfect match for this.

I am working with the Play framework and it uses JPA2 backed by hibernate.

My problem right now is that I can't seem to get Hibernate to generate the Sequences as part of the automatic ddl update on start of the application.

Every documentation I can find about using @SequenceGenerator seems to be related to the Entity Id, and not how to define a sequence independent of the one used for the entity id.

Thanks.

EDIT: Just to give more context for the question, what I am doing is a implementing a service for keeping highscores, the first time a player starts the game it will ask the server for a guest account.

Guest accounts have a username in the form of player + number like "player123123" where the number would be generated from the sequence that I am trying to use.

When the user registers he will be able to change the username to something custom, but not in the form of player + anything, so that the namespace player + number remains free to use for guest accounts.

EDIT2: For now I got it to work by defining an extra useless entity that will never be used and just use the Sequence from that entity, but it is an ugly hack.

Ignoring possible solutions (hacks) for my concrete problem, I would like to know if it is possible with hibernate and jpa2 to declare extra (not the one used for id generation) sequences asociated to an entity or independent from any entity and have hibernate create them in the db automatically.

Upvotes: 2

Views: 857

Answers (2)

Pere Villega
Pere Villega

Reputation: 16439

Play adds automatically a numeric id to the class when you extend Model.

Given that you don't mind gaps and you only need the numeric sequence, I would suggest to use the id Play provides as the reference for your sequence.

NOTE: I'm assuming in here that you want that sequence linked to an entity which may contain more data. If that's not the case, this may not work.

Upvotes: 0

tmbrggmn
tmbrggmn

Reputation: 8830

Sequence generators (defined using @SequenceGenerator) should be unique across the entire persistence unit, so you could re-use them. This question deals with this (more or less) specific issue.

A couple of things to keep in mind:

  • Sequences are not supported by all database vendors, I believe Oracle and PostgreSQL support them but I'm not sure about the others
  • Sequence generator can only be defined on entities, so you can't use a @MappedSuperclass
  • Play framework will automatically add and ID field to your entities if you extend Model, so keep that in mind in case you want to override that behaviour

Upvotes: 1

Related Questions