Thursday, February 6, 2014

Correct way to use DB sequences in JPA

I have a sequence defined in an existing database (mine is PostgreSQL) for the primary key. I want to use JPA (implemented by Hibernate) to use this sequence when persisting (inserting) a new object.

The below is the correct way to do it.

First, basic JPA stuff. The column name.

Next, we need to have 2 annotations @GeneratedValue and @SequenceGenerator. With the former referring to the latter. It looks a little redundant to me, but hey... I'm just a programmer.

Third, we specify the the sequence name (as in the DB). We need to include the schema as well.

Finally, we specify the increment.

ps. I seem to need to restart the server (Glassfish 3) almost each time I make changes to JPA annotations (it was giving me "XxxXxx class is not recognized by Java persistance" etc etc). So if the above doesn't work for you, try restarting the server first.

No comments:

Post a Comment