0

Context: Java EE application should minimize the risk of data loss as much as possible. This can come at the cost of performance for now, as the load on the server is not that high.

My understanding is that GenerationType.IDENTITY performs an immediate insert operation into the database when the Object is instantiated, whereas GenerationType.SEQUENCE performs a read operation on the database to retrieve the next value of a database sequence. The source used for this information is from here. Please correct me if my understanding is wrong.

Given my understanding, should GenerationType.IDENTITY be preferred over GenerationType.SEQUENCE in this context since data is persisted to the database earlier?

Lee He
  • 181
  • 12
  • The short answer is that this depends on the database. For example, Mysql doesn't support sequences, Oracle doesn't support AUTOINCREMENT columns so sequences are the only choice, I think Postgress supports both and when autoincrement is used a sequence is used under the hood . – garfield Aug 10 '18 at 05:03
  • It depends on the JPA provider also. Also IDENTITY will mean that you cannot take advantage of batch inserts –  Aug 10 '18 at 08:50
  • Thanks! Hibernate is the JPA provider. I will go with AUTO instead, and let Hibernate make a judgement. – Lee He Aug 14 '18 at 06:30

1 Answers1

1

Hibernate persists data immediately for entities marked with GenerationType.IDENTITY as Hibernate needs to know the primary key value to maintain the session. But this has flaw, as this generation type wont be able to use many Hibernate optimization techniques.

For entities marked with GenerationType.SEQUENCE, Hibernate internally fires a select query when an object is persisted using session.save() or session.persist() and populates the primary key. Then it can save the data when the session is Flushed/Committed. Moreover, since the entity is being populated with the primary key , Hibernate can internally use optimization techniques on these entities like JDBC Batching and all.

More information can be seen here - https://www.thoughts-on-java.org/jpa-generate-primary-keys/

Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30
  • 1
    Thanks! Had a look at the [Hibernate docs](http://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators) too, which had additional caveats regarding GenerationType.IDENTITY. Will leave it on AUTO instead in this case, and let Hibernate make a judgement. – Lee He Aug 14 '18 at 06:29