Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the way Spring Data JPA sets the default values of fields?

Shulou Source: shulou.com Published: 2022-06-02 10:40:37 10月23日 Update

This article shows you how to set field defaults in Spring Data JPA. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Spring Data JPA sets field default values

Write the following two attributes in the Column comment, why check the document yourself, you can set the default value of the field, and by the way solve the problem that the field is automatically populated as null in the sql statement generated by the save method.

The default values cannot be updated, so if you want to change the field defaults in the code, you need to rebuild the table.

@ Column (insertable = false,columnDefinition = "int default 1") private Integer sex; @ Column (insertable = false,columnDefinition = "decimal DEFAULT 0.00") private BigDecimal accountBalance;// account balance

ColumnDefinition = "creter table DDL statement equivalent to database"

CREATE TABLE `account_ info` (`id` int (11) NOT NULL AUTO_INCREMENT,. . . . `account_ balance` decimal (197.2) DEFAULT '0.005,. . . . PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;Spring Data JPA failed to set field default value

The annotation used to set default values for jpa annotations is @ Column. But one problem is that if you have already created the table, it is useless to add @ Column (insertable = false,columnDefinition = "int default 1"), because this annotation only works when the table is created, that is, if the table has been built in DB, this property is not necessary.

@ Column (columnDefinition= "int default 1", nullable=false) private int number

Therefore, it is best to add logical operations when writing save () or update ().

The above is how Spring Data JPA sets the default values of fields. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Fields annotations methods content that is attributes skills knowledge statements questions concise necessary concise two in the table that is code balance function Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MariaDB macOS Redmi Huawei