Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to set the default value for Spring Data JPA

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

本篇内容主要讲解"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怎么设置默认值"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report