Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Hibernate from using 0 as ID?

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?

like image 330
Brian Johnson Avatar asked Oct 09 '22 11:10

Brian Johnson


1 Answers

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.

like image 101
ManuPK Avatar answered Oct 18 '22 09:10

ManuPK