spring-projects / spring-data-relational

Spring Data Relational. Home of Spring Data JDBC and Spring Data R2DBC.
https://spring.io/projects/spring-data-jdbc
Apache License 2.0
772 stars 346 forks source link

How to achieve @DynamicInsert effect in Spring Data JDBC? #1522

Open CanvaChen opened 1 year ago

CanvaChen commented 1 year ago

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!

schauder commented 1 year ago

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?

CanvaChen commented 1 year ago

@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.
schauder commented 1 year ago

This should be implemented as using an attribute of the @Column annotation, similar to [Spring Data MongoDbs @Field.write](https://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Field.html#write())