简体   繁体   中英

How to validate if a nested referenced object (@ManyToOne) exists with OpenXava/JPA?

In my OpenXava application I have a class called Parcel that references TaxAccount class:

@Entity 
public Parcel {

    @ManyToOne
    TaxAccount taxAccout;

}

Also, I have a class called Assessment that references Parcel:

@Entity
public class Assessment {

    @ManyToOne
    Parcel parcel;

}

When saving Assessment I would like to check/validate if the referenced Parcel has a TaxAccount linked to it. If referenced Parcel has a TaxAccount then save action of Assessment should be successful else the save action should fail.

How do I achieve this with OpenXava?

The easiest way is to include the validation in the entity itself, in this way:

public class Assessment {

    @AssertTrue(message="parcel_must_have_tax_account")
    private boolean parcelHasTaxAccount() {
        return parcel != null && parcel.getTaxAccount() != null;
    }

}

Note as @AssertTrue is not an OpenXava annotation but a Bean Validation annotation, so this validation will work with OpenXava but also when you use your JPA entities outside of OpenXava.

For more validation alternatives in OpenXava look at:

https://openxava.org/OpenXavaDoc/docs/validation_en.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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