简体   繁体   English

JPA Embedded和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;

    [...]
}

I need to save the class Poo as null in the database and consequently any attribute that already exists in the table is converted to null. 我需要将类Poo保存为数据库中的null,因此表中已存在的任何属性都将转换为null。 It's possible? 这是可能的?

The only way I could do it was to remove @NotNull from the attributes and set each attribute itself to null. 我能做到的唯一方法是从属性中删除@NotNull并将每个属性本身设置为null。

Just had the same problem and I solved it by adding an Annotation like @NotNull just underneath the annotation @Valid 刚出现同样的问题,我通过在注释@Valid下添加@NotNull之类的注释来解决它

    @Entity    
public class Foo {

    [...]

    @Valid
    @Embedded
    @NotNull
    private Poo poo;
}

@Embeddable
public class Poo {

    @NotNull
    private Double value;

    @NotNull
    private Double value2;

    [...]
}

By default for me it works exactly as you said. 默认情况下,它完全按照你的说法工作。 I just tested it with MariaDB and: 我刚用MariaDB测试它并且:

   <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.0</version>
    </dependency>

And here's my test code: 这是我的测试代码:

    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);

But if you still have a problem, please, provide your test scenario and check out this post: https://stackoverflow.com/a/40979958/7974082 . 但是,如果您仍有问题,请提供您的测试方案并查看此帖子: https//stackoverflow.com/a/40979958/7974082

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM