0

I have a table named GROUPS which has a column GROUP_ID whose values are

GRP001, GRP002, GRP003

and so on. Now every time I insert a new row I have to insert it with a (current) GROUP_ID= (highest)GROUP_ID+ 1 , for example if highest GROUP_ID= GRP003 I have to generate a new GROUP_ID GRP004 when I insert a new row.

How can I do this using java?

I am currently using Hibernate along with Struts 2 in my program

Is there any way to deal with this using hibernate? Or will I have to write additional code to lock the table, check the db for max Id (and then increment it) and finally release the lock?

user2077648
  • 951
  • 7
  • 27
  • 42
  • What database is this running on? Look at this question - http://stackoverflow.com/questions/6346450/how-to-get-the-auto-increment-primary-key-value-in-mysql-using-hibernate You can probably write a class to generate keys. not sure. Why must the group id have "GRP" preceding it instead of just a straight sequence #? – OldProgrammer Mar 31 '13 at 16:09
  • This application is supposed to be database independent that why I am using Hibernate and it is predefined that group id should have "GRP" preceding it. – user2077648 Mar 31 '13 at 16:35

1 Answers1

1

I remember solving a problem similar to this once. What I did was I create a custom primary key generator as supported by hibernate.

This guy explains it clearly here: "Custom Hibernate Primary Key Generator"

Basically you just need to implement org.hibernate.id.IdentifierGenerator and all should be set.

Just be aware that the solution implemented in the example above is database dependent. But I think sometimes common sense should prevail over overengineering.

Rosdi Kasim
  • 24,267
  • 23
  • 130
  • 154
  • I read the link you suggested, but I did not get this point "First I created a database sequence to use. Then I implemented org.hibernate.id.IdentifierGenerator" , where do I need to create this sequence? Is it on GROUPS table and how? – user2077648 Mar 31 '13 at 17:11
  • Most databases have a sequence generation function either as a native object, or a function call. You may have to write a custom tenerator per database type to generate a sequence. – OldProgrammer Mar 31 '13 at 17:25
  • @user2077648 `sequence` is mostly an Oracle thing, so make sure you are using Oracle. For more explanation about sequence refer here: http://stackoverflow.com/questions/798766/how-to-create-an-oracle-sequence-starting-with-max-value-from-a-table – Rosdi Kasim Mar 31 '13 at 17:26
  • I am not allowed to implement a sequence for my table – user2077648 Apr 01 '13 at 23:57