JPA 嵌入式和 BeanValidation
JPA Embedded and BeanValidation
@Entity
public class Foo {
[...]
@Valid
@Embedded
private Poo poo;
}
@Embeddable
public class Poo {
@NotNull
private Double value;
@NotNull
private Double value2;
[...]
}
我需要在数据库中将 class Poo 保存为 null,因此 table 中已经存在的任何属性都将转换为 null。可能吗?
我能做到的唯一方法是从属性中删除 @NotNull 并将每个属性本身设置为 null。
默认情况下对我来说它完全按照你说的工作。我刚刚用 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);
但如果您仍然遇到问题,请提供您的测试场景并查看此 post:
.
刚遇到同样的问题,我通过在注解@Valid
下面添加一个像@NotNull 这样的注解来解决它
@Entity
public class Foo {
[...]
@Valid
@Embedded
@NotNull
private Poo poo;
}
@Embeddable
public class Poo {
@NotNull
private Double value;
@NotNull
private Double value2;
[...]
}
@Entity
public class Foo {
[...]
@Valid
@Embedded
private Poo poo;
}
@Embeddable
public class Poo {
@NotNull
private Double value;
@NotNull
private Double value2;
[...]
}
我需要在数据库中将 class Poo 保存为 null,因此 table 中已经存在的任何属性都将转换为 null。可能吗?
我能做到的唯一方法是从属性中删除 @NotNull 并将每个属性本身设置为 null。
默认情况下对我来说它完全按照你说的工作。我刚刚用 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);
但如果您仍然遇到问题,请提供您的测试场景并查看此 post: .
刚遇到同样的问题,我通过在注解@Valid
下面添加一个像@NotNull 这样的注解来解决它 @Entity
public class Foo {
[...]
@Valid
@Embedded
@NotNull
private Poo poo;
}
@Embeddable
public class Poo {
@NotNull
private Double value;
@NotNull
private Double value2;
[...]
}