spring-data-relational icon indicating copy to clipboard operation
spring-data-relational copied to clipboard

How to achieve @DynamicInsert effect in Spring Data JDBC?

Open CanvaChen opened this issue 1 year ago • 3 comments

Hello,

I would like to open an issue to inquire about the implementation of the "@DynamicInsert" effect in Spring Data JDBC.

@DynamicInsert is an annotation commonly used in Hibernate, which allows for selective insertion of entity fields based on their values. In other words, only non-null fields are inserted into the database during an "INSERT" operation, while null fields are excluded. I'm wondering if there is a similar functionality available in Spring Data JDBC.

I have gone through the Spring Data JDBC documentation but couldn't find any specific annotation or configuration option that replicates the behavior of "@DynamicInsert" in Hibernate. Could you kindly provide some guidance on how to achieve a similar effect in Spring Data JDBC? Are there any built-in mechanisms or recommended approaches to accomplish this selective insertion behavior?

Any insights, suggestions, or code examples you can provide would be highly appreciated. Thank you for your time and assistance.

Best regards!

CanvaChen avatar May 25 '23 15:05 CanvaChen

It depends on your actual requirements.

There is @ReadOnlyProperty which marks a property as not to be used during insert or update operations. Of course that is not dynamic and as said also affects update.

The final option is to create your insert statement yourself in a custom method implementation.

What is the business requirement behind using @DynamicInsert?

schauder avatar May 30 '23 08:05 schauder

@schauder Thank you. I have achieved the effect of dynamic insertion through custom implementation. My scenario is as follows:

  1. Many people are used to setting most of the table fields as not null and setting default values.
  2. When inserting, some fields need to be assigned values, and when updating, other fields need to be set.
  3. If the fields that are currently not of concern are not assigned values during insertion, it will cause the save to fail.

CanvaChen avatar May 31 '23 14:05 CanvaChen

This should be implemented as using an attribute of the @Column annotation, similar to Spring Data MongoDbs @Field.write

schauder avatar Jun 01 '23 10:06 schauder