2 Replies Latest reply on Apr 15, 2011 10:12 AM by djhill

    ID Generation - best practices?

    djhill

      I recently modified a case study in an EJB3 course where the initial code had 3 entities, only one of which specified an ID generation strategy (sequence). This was the only entity persisted in the case study. Curiously, the script that was used to initially populate the database defined an ID_GEN table with rows for each entity, but it wasn't being used.

       

      This approach seemed lazy, and was problematical in that Hibernate created a sequence and table that were not in the initialization script. Since we were using DefaultDS (to eliminate some setup activities), the end result was that students would have to delete all the LocalDB files if they had to repopulate the database, Being students, they probably would have had to do this multiple times.

       

      In the end I modified the case study entities to use a TableGenerator, but wondered what others consider a best practice. Is a sequence strategy preferred? I know that a while back it wasn't universally supported on the back end.

       

      In my personal experience we generally had existing models and depended on the facilities of the back-end (or triggers). I'd be interested to hear your opinions and experiences with the various EJB3 strategies.

        • 1. ID Generation - best practices?
          wdfink

          Best practice - depends to your environment.

           

          If you use @Id and @GeneratedValue the container decide how to do it depended to the database, e.g. autoincrement DB fields.

           

          We use

           

          @Entity

          @SequenceGenerator(name = "MySequence", sequenceName = "MY_SEQ", initialValue = 1, allocationSize = 1)

          class MyClazz {

            @Id

            @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MySequence")

            long myPk;

          }

           

          because of use Oracle and defined DB sequences.

          • 2. ID Generation - best practices?
            djhill

            Thanks, Wolf-Dieter.

             

            That was the strategy applied to the one table in the original code, and it does simplify coding. But because the ID_GEN table was also present, I couldn't tell if the original author was planning to go in one direction or the other. For that one entity (Salary), Hibernate created a sequence and a table DUAL_SALARY_SEQ, so I have to assume that similar sequences and tables would be created for all entities, possibly resulting in a proliferation of SEQ tables.

             

            I'd be curious to hear whether a single table (which is likely to be cached) might offer better performance. Has anyone compared the two?