gpt4 book ai didi

java - 如何在 JPA 中设置默认 boolean 值

转载 作者:IT老高 更新时间:2023-10-28 21:14:09 24 4
gpt4 key购买 nike

我有一个属性

private boolean include;

我想将其默认值设置为 true,以便在数据库中它必须从默认值显示 True。这在 JPA 中可行吗?

最佳答案

据我所知,没有提供默认值的 JPA 原生解决方案。这是我的解决方法:

非数据库可移植解决方案

@Column(columnDefinition="tinyint(1) default 1")
private boolean include;

面向 Java 的解决方案

private boolean include = true;

面向 Java 的加 Builder 模式

     @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 模式定义默认值。

关于java - 如何在 JPA 中设置默认 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com