Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not Hibernate set @DynamicInsert by default

Could anyone explain to me why Hibernate does not set the @DynamicInsert annotation by default and allow entities to generate an INSERT based on the currently set properties?

What's the reason for not using @DynamicInsert and, therefore, including all entity properties by default?

like image 614
Venkatesh Avatar asked Feb 12 '14 07:02

Venkatesh


3 Answers

What @jb-nizet said.

Also, dynamic-insert="true" is a bad idea in my book.

Skipping null fields from the generated SQL, soon you will find yourself in a situation where you will be declaring columns not null default which in fact causes the persistent data to be different than the entity data that hibernate knows about. This will cause frustration and likely make you resort to expensive session.refresh() calls.

For example suppose column

MESSAGE varchar(64) not null default ''

and you save an entity with null value for the property that is mapped to this column.

With dynamic-insert you will end up with an entity that has null value for the property message in-memory while at the same time the corresponding database row has ''.

I hope I made sense. Especially if you are considering dynamic-insert for such a scenario (to get away from having to set all properties for not null columns and rely on a default constraint), think again.

like image 59
dkateros Avatar answered Oct 17 '22 08:10

dkateros


The dynamic inserts and updates are very useful for two reasons:

  • reducing OptimisticLockException false positives on non-overlapping write-concern property sets
  • avoiding some processing overhead related to updating indexes

However, the dynamic insert/update have drawbacks as well:

  • you cannot reuse server-side and client-side prepared statements
  • it reduces the likelihood of benefiting from batch updates] since the statement might change from one entity to the other.

So, there is no good way or bad way. It just depends on your data access patterns to figure out which of these two makes sense for a given entity.

like image 27
Vlad Mihalcea Avatar answered Oct 17 '22 10:10

Vlad Mihalcea


Because it doesn't add any significant performance improvement to skip null fields when inserting an entity.

To the contrary, it can decrease performance because, instead of being able to always use the same prepared statement to insert a row in a table, and be able to execute several inserts into a single batch, Hibernate must create a specific prepared statement for each entity to insert, which depends on the fields that are null and the fields that are not.

So, more complexity, for a reduced performance.

like image 24
JB Nizet Avatar answered Oct 17 '22 10:10

JB Nizet