Home > database >  Is there a way in SpringBoot to add default data for fields while the entity class is being created?
Is there a way in SpringBoot to add default data for fields while the entity class is being created?

Time:01-23

This is My entity class, this represents the account which upadtes the accountBalance based on the transactions happen on one more entity,

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MainAccounts {
     @Id
        private Long id  ;
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        private LocalDate date
        private Double AccountBalance;
        
       
        public Double getAccountBalance() {
            return AccountBalance;
        }
        public void setAccountBalance(Double accountBalance) {
            AccountBalance = accountBalance;
        }
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public LocalDate getDate() {
            return date;
        }
        public void setDate(LocalDate date) {
            this.date = date;
        }
        

Once the entity is created, can i able to add default values to my accounts table,like this?

id date accountBalance
1 null 0.00

simply i dont want the table to have null values,when i invoke getId(), or getaccountBalance() methods

CodePudding user response:

you are using @Data already which means you don't need to write the getter and setter manually, because the Lombok will generate it in the background just use setDate(your date here), and apply the same concept on all the getters and setter methods,

Note: if the date will represent the creation date you can use this annotation to set above date variable @CreationTimestamp

CodePudding user response:

Actually you can set it thanks to @Column annotation.

https://www.baeldung.com/jpa-default-column-values

To create a default value directly in the SQL table definition, we can use the @Column annotation and set its columnDefinition parameter:
    @Column(columnDefinition = "varchar(255) default 'John Snow'")
    private String name;

    @Column(columnDefinition = "integer default 25")
    private Integer age;
  • Related