1 Reply Latest reply on Mar 5, 2007 3:44 AM by Rabbia Qaswar

    How to use @Id @GeneratedValue(strategy=GenerationType.AUTO)

    Tony Mai Apprentice

      How does the id get generated?

      Say I have a simple entity bean with 2 attributes id and desc. Attribute id is tagged with @Id @GeneratedValue(strategy=GenerationType.AUTO).

      Can I create a new object of this class with just the desc and let Hibernate create the id? In the database end, do I create the table for this entity with column id declared as bigint?

      Thanks in advance for your help.

        • 1. Re: How to use @Id @GeneratedValue(strategy=GenerationType.A
          Rabbia Qaswar Newbie

          When you will create your entity you will only have to set the desc property. The 'id' property will be set since it has these @Id @GeneratedValue(strategy=GenerationType.AUTO) annotations.

          The database end depends upon the table generation strategy in your persistence.xml file. If this is what you have in persistence.xml:

          <properties>
           <property name="hibernate.hbm2ddl.auto" value="create"/>
          </properties>
          

          OR
          <properties>
           <property name="hibernate.hbm2ddl.auto" value="update"/>
          </properties>


          Then you dont have to create the tables yourself, they'll be created. If you want to create the tables yourself then just like anyother column in a table you should also create the column for your id.

          The @GeneratedValue annotations generates only int, Long or String values(but do check for yourself). So you should check what should be the datatype of your id. Say i have a table Customer in db with property Number CUSTOMERID. In my entity Customer, i will have property Long customerId. Then i use:

          @Id
          @GeneratedValue(strategy=GenerationType.AUTO)


          It works fine.

          hope this helps!