Get the App
SLTechnology News&Howtos  ›  Development  › 

How to set the default value for Spring Data JPA

Shulou Source: shulou.com Published: 2022-06-02 11:52:39 09月19日 Update

本篇内容主要讲解"Spring Data JPA怎么设置默认值",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"Spring Data JPA怎么设置默认值"吧!

Spring Data JPA设置默认值的问题

我有一个entity实体,其中里面有一个布尔类型的字段:

//entity table注解略public class TableEntity { private Boolean b; public Boolean getB() { return b; } public void setB(Boolean b) { this.b= b; }}

然后现在是需要给这个布尔型变量设默认值true

一开始经过百度,写法是这样的//entity table注解略public class TableEntity { @Column(name = "b", columnDefinition = "bit default 1", nullable = false) private Boolean b; public Boolean getB() { return b; } public void setB(Boolean b) { this.b= b; }}

这个写法其实应该没什么问题,当时的数据库是sql server,但是在换环境部署,切换到MySQL的时候出了问题,被怀疑是我这里写的问题(其实我总感觉应该没什么关系)

于是改了第二版//entity table注解略public class TableEntity { @Column(name = "b", nullable = false) @org.hibernate.annotations.Type(type = "yes_no") private Boolean b = true; public Boolean getB() { return b; } public void setB(Boolean b) { this.b= b; }}

直接把私有属性值赋值,这也是通过百度之后,有部分文章说的一种方法,至于type那个注解,就是把布尔型变量在数据库中通过字符型变量来存储,存储"Y"或者"N"。

但是这个写法,工程跑起来之后还是有问题的,存不上默认值,等于白写。

在大佬的指点下,有了第三种写法//entity table注解略public class TableEntity { @Column(name = "b", nullable = false) @org.hibernate.annotations.Type(type = "yes_no") private Boolean b = true; public Boolean getB() { if(b==null) { return true; } return b; } public void setB(Boolean b) { if(b==null) { return; } this.b= b; }}

大概意思是,在JPA进行保存的时候框架内部会自己调用get/set方法来进行属性赋值和取值,所以直接在get/set方法进行默认值的赋值就可以了。

实际测试效果拔群。

Jpa设置默认值约束

使用SpringDataJpa设置字段的默认值约束的2种方式

1、修改建表时的列定义属性@Column(columnDefinition="INT DEFAULT '1'")private Integer status;2、通过Hibernate(org.hibernate.annotations.ColumnDefault)

下提供的注解进行设置默认值

@ColumnDefault("1")private Integer status;到此,相信大家对"Spring Data JPA怎么设置默认值"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Tags: Comments questions writing methods variables attributes Boolean nothing content fields actual data database time storage learning character type practical deeper interest Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia MariaDB vpn Linux Shulou Information