I'm new to hibernate. I do not understand the the following two primary key generation strategies:
Can someone please explain how these two work and what is the difference between these two?
The IDENTITY property is tied to a particular table and cannot be shared among multiple tables since it is a table column property. On the flip side the SEQUENCE object is defined by the user and can be shared by multiple tables since is it is not tied to any table.
The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example when using Mysql , you may specify auto_increment in the definition of table to make it self-incremental, and then use @GeneratedValue(strategy = GenerationType.IDENTITY)
GenerationType. SEQUENCE in hibernate generates the sequence for the primary column of the table. We need to create a sequence generator in database and refer that name in the code. The syntax of GenerationType.
AUTO (default): Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite and MsSQL and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability. SEQUENCE: Tells Doctrine to use a database sequence for ID generation.
Quoting Java Persistence/Identity and Sequencing:
Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.
In plain English: you mark at most one ID
column in your table as IDENTITY. The database engine will put next available value for you automatically.
And:
Sequence objects use special database objects to generate ids. Sequence objects are only supported in some databases, such as Oracle, DB2, and Postgres. Usually, a SEQUENCE object has a name, an INCREMENT, and other database object settings. Each time the
<sequence>.NEXTVAL
is selected the sequence is incremented by the INCREMENT.
Sequences are more flexible and slightly more complex. You define an extra object in your database next to tables, triggers, etc. called sequences. Sequences are basically named counter you can use anywhere inside queries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With