如何在JPA中设置默认布尔值

如何在JPA中设置默认布尔值

本文介绍了如何在JPA中设置默认布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性

private boolean include;

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

I would like to set its default value to true, so that in the database it must display True from default. Is this possible in JPA?

推荐答案

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

As far as i known there is no JPA native solution to provide default values.Here it comes my workaround:

非数据库便携式解决方案

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

This is my favorite and less intrusive. Basically it delegates the task to define the default value to the Builder pattern in your entity.

这篇关于如何在JPA中设置默认布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 03:18