![](/img/trans.png)
[英]how to set default value for Boolean in java without using constructor
[英]How to set default boolean value in JPA
我有一個屬性
private boolean include;
我想將其默認值設置為 true,以便在數據庫中它必須默認顯示 True。 這在 JPA 中是否可行?
據我所知,沒有提供默認值的 JPA 本機解決方案。 這是我的解決方法:
非數據庫便攜解決方案
@Column(columnDefinition="tinyint(1) default 1")
private boolean include;
面向Java的解決方案
private boolean include = true;
面向 Java 的加構建器模式
@Column(nullable = false)
private Boolean include;
...
public static class Builder {
private Boolean include = true; // Here it comes your default value
public Builder include (Boolean include ) {
this.include = include ;
return this;
}
// Use the pattern builder whenever you need to persist a new entity.
public MyEntity build() {
MyEntity myEntity = new MyEntity ();
myEntity .setinclude (include );
return myEntity;
}
...
}
這是我最喜歡的,不那么侵入性。 基本上,它將定義默認值的任務委托給實體中的 Builder 模式。
使用 JPA 2.1 和 Oracle 11 這通過使用大小為 1 的 Oracle 類型 NUMBER 對我有用:
爪哇:
@Column(name = "ENABLED", nullable = false)
private boolean enabled = true;
創建 SQL 腳本:
CREATE TABLE "ACCOUNT"(
"ID" NUMBER(10,0) NOT NULL ENABLE,
"NAME" VARCHAR2(255 CHAR) NOT NULL ENABLE,
"PASSWORD" VARCHAR2(255) NOT NULL ENABLE,
"ENABLED" NUMBER(1,0) DEFAULT 1 NOT NULL ENABLE,
PRIMARY KEY ("ID")
);
對於PostgreSQL,您可以在定義中使用 boolean
@Column(name = "isDeleted", columnDefinition = "boolean default true")
private boolean isDeleted = true;
我發現在構造函數中添加是一個很好的解決方法,可以將新實體默認為一個值:
public EntityName(){
this.fieldToDefault = default;
}
也許對使用 Microsoft SQL SERVER 的人有用
@Column(columnDefinition="bit default 0")
private Boolean active;
可能的值:0 或 1
您始終可以在方法上使用@PreUpdate
或@PrePersist
注釋,您可以在其中設置在更新之前或保存到數據庫之前應該做什么。
或者只是簡單地設置值private boolean include = true;
如果您在數據庫中定義了默認值,則可以選擇列注釋,並使用insertable = false
作為參數,這樣在插入值時,它將選擇您在數據庫中默認標記的值。 示例:在 MySQL 中,我有一個帶有布爾類型狀態屬性的人員表,默認情況下它的值為 true。 在您的 Java 類中,它看起來像這樣:
//....
public class Person implements Serializable {
//.....
@Column(insertable = false)
private Boolean status;
//...
}
您可以在此處獲得有關列注釋的更多信息,它得到了很好的解釋,對我幫助很大。
設置默認列值的簡單方法是將其直接設置為實體屬性值:
@Entity
public class Student {
@Id
private Long id;
private String name = "Ousama";
private Integer age = 30;
private Boolean happy = false;
}
就我而言,對於 spring boot jpa,在實體類中使用以下語法。
@Builder.Default
private boolean columnName = false;
or
@NotNull
@Builder.Default
@ColumnDefault("true")
private Boolean columnName = true;
@Builder.Default 是為了確保我們在為這個模型構造對象時有默認值,只有當實體模型類用@Builder 注釋時才需要。 否則,即使沒有@Builder.Default,事情也能按預期正常工作。
如果您使用的是 MYSQL,我可以為您節省 5-6 個小時,如果您正在尋找答案,您將浪費這些時間。 I tried multiple ways but for me updating the maven dependency version of spring boot data jpa in pom.xml file
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.7.3</version>
</dependency>
private boolean include = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.