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?
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.
The dynamic inserts and updates are very useful for two reasons:
OptimisticLockException
false positives on non-overlapping write-concern property setsHowever, the dynamic insert/update have drawbacks as well:
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.
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.
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