Why does not Hibernate set @DynamicInsert by default
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.
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.
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.