@Entity
public class Foo {
[...]
@Valid
@Embedded
private Poo poo;
}
@Embeddable
public class Poo {
@NotNull
private Double value;
@NotNull
private Double value2;
[...]
}
我需要将类Poo保存为数据库中的null,因此表中已存在的任何属性都将转换为null。有可能吗?
我能做到的唯一方法是从属性中删除@NotNull并将每个属性本身设置为null。
答案 0 :(得分:2)
遇到同样的问题,我通过在注释@Valid下方添加一个类似@NotNull的注释来解决了该问题
@Entity
public class Foo {
[...]
@Valid
@Embedded
@NotNull
private Poo poo;
}
@Embeddable
public class Poo {
@NotNull
private Double value;
@NotNull
private Double value2;
[...]
}
答案 1 :(得分:0)
默认情况下,它的工作方式与您说的完全相同。我刚用MariaDB测试了它:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
这是我的测试代码:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Foo foo = new Foo(1, new Poo(1, 2));
validate(validator, foo);
entityManager.merge(foo);
List<Foo> fooList = entityManager
.createNamedQuery(Foo.FIND_ALL, Foo.class)
.getResultList();
assertTrue(fooList.get(0).getPoo().getValue1() == 1);
foo.setPoo(null);
validate(validator, foo);
entityManager.merge(foo);
fooList = entityManager
.createNamedQuery(Foo.FIND_ALL, Foo.class)
.getResultList();
assertTrue(fooList.get(0).getPoo() == null);
但是,如果您仍有问题,请提供您的测试方案并查看此帖子: https://stackoverflow.com/a/40979958/7974082。