有没有办法防止空值被持久化,同时允许其他人通过? [英] Is there a way to prevent null values from being persisted while allowing others through?

查看:20
本文介绍了有没有办法防止空值被持久化,同时允许其他人通过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的 JPA (EclipseLink) 项目,其中所需的行为是,如果在实体的字段中给定空值,则不应保留该空值.

I have an existing JPA (EclipseLink) project where the desired behaviour is that if given a null value in a field for an entity, that null value should not be persisted.

用例是我们可能会从外部来源获得这些实体的几个部分更新.这些来源可能会给我们一个空值,这并不意味着取消这个字段",而是我没有这个值".

The use case is that we may get several partial updates to these entities from external sources. Those sources may give us a null value, that does not mean "nullify this field" it means "I don't have this value".

是否有可用于在 setter 中自动执行空检查或告诉 JPA 不要保留空值的注释、模式或其他工具????

Is there an annotation, pattern, or other tool that can be used to automate a null check in the setter OR tell JPA to not persist null values????

我可以通过每个实体中的每个 setter 并添加 if(val != null) {//set the value } 但这很乏味和重复.

I can go through EVERY setter in EVERY entity and add if(val != null) { //set the value } but that is tedious and repetitive.

例如我们有:


@Entity
@Table(name = "my_table")
public class MyObject {
 @Column
 private String myColumn;

 public String getMyColumn() {
  return this.myColumn;
 }

 public void setMyColumn(String val) {
  this.myColumn = val;
 }
}

我想要一些可以自动提供帮助的东西:

I would like to have something that would automatically help like this:


@Entity
@Table(name = "my_table")
public class MyObject {
 @Column
 @DontPersistIfNull
 private String myColumn;

 public String getMyColumn() {
  return this.myColumn;
 }

 public void setMyColumn(String val) {
  this.myColumn = val;
 }
}

或者这个:


@Entity
@Table(name = "my_table")
public class MyObject {
 @Column
 private String myColumn;

 public String getMyColumn() {
  return this.myColumn;
 }

 public void setMyColumn(String val) {
  //AUTOGENERATED NULL CHECK
  if(val != null) {
   this.myColumn = val;
  }
 }
}

推荐答案

Hibernate 验证器 (和 javax.validation) 的任何实现都有 @NotNull 注释,如果注释的属性为空,则不允许持久化实体.我不确定 hibernate-validator 是否可以与 EclipseLink 一起使用,但也应该有一个用于 EclipseLink 的 javax.validation 实现.

Hibernate validator (and any implementation of javax.validation) has the @NotNull annotation, which will disallow the entity to be persisted if the annotated property is null. I'm not sure of hibernate-validator would work with EclipseLink, but there should be an implementation of javax.validation for EclipseLink as well.

但是如果您想阻止设置空值 - 好吧,那么请修改设置值的图层,而不是实体本身.

But if you want to block setting nulls - well, then modify the layer that sets the values, rather than the entities themselves.

这篇关于有没有办法防止空值被持久化,同时允许其他人通过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆