5

I am using

@TableGenerator(name="tab",initialValue=2,allocationSize=50)

on Entities and define the ID with

@Id
@GeneratedValue(generator="tab",strategy=GenerationType.TABLE)
private int id;

yet Hibernate still uses 0 as an ID.

I cannot use @GenericGenerator because the annotations do not come with Hibernate4 that ships with Jboss AS7.

Is there a simple solution or do I have to write a custom Generator?

Brian Johnson
  • 1,629
  • 5
  • 21
  • 26
  • 1
    Don't you have any deployment descriptor code that overrides your annotation? Are you using a schema initialization or work on existing database? – Piotr Nowicki Nov 17 '11 at 08:22
  • No database-specific deployment descriptor. I am using and use some sample data via import.sql for now. – Brian Johnson Nov 18 '11 at 22:31
  • And you're sure that among these data there aren't any inserts to the table where table generator resides? Did you try invoking the code on empty database to let the Hibernate generate all tables and before the import.sql is executed? – Piotr Nowicki Nov 18 '11 at 22:46
  • See http://stackoverflow.com/questions/3433724/proper-hibernate-id-generator-for-postgres-serial-bigserial-column/3435358#3435358 (I had the same problem--I wanted to use hibernate SERIAL primary key, but hibernate kept on inserting 0's for the id--setting it to what the link describes and now my inserts work with postgres) – rogerdpack May 13 '14 at 19:56

1 Answers1

4

Hibernate is creating ids with id 0 because you have a primitive type. Try using Integer id instead of int id. Remember primitives can't hold a null value.

If you want to generate the custom id generator, you can use a SEQUENCE in DB to generate the id if the object.

<id ....>
        <generator class="sequence">
           <param name="sequence">YOUR_SEQUENCE _NAME</param>
       </generator>
</id>

Read the API about generator classes here.

ManuPK
  • 11,623
  • 10
  • 57
  • 76
  • Thanks. The question is more or less if it requires a custom generator to tell Hibernate not to use 0 as an ID and why it ignores the generator annotations. – Brian Johnson Nov 18 '11 at 22:34