ich ein Unternehmen wie dies bekam:individuelle JPA Validierung im Frühjahr Boot
@Entity
@Table(name = "transaction_receiver")
public class TransactionReceiver implements Serializable, Addressable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "contact_id", nullable = false)
private String contactId;
@Column(name = "datev_number")
private String datevNumber;
@NotNull
@Column(name = "receiver", nullable = false)
private String receiver;
@NotNull
@Size(min = 22, max = 34)
@Column(name = "iban", length = 34, nullable = false)
private String iban;
@Size(min = 8, max = 11)
@Column(name = "bic", length = 11, nullable = false)
private String bic;
@NotNull
@Column(name = "institute")
private String institute;
@Column(name = "company")
private String company;
und die Aufgabe, eine benutzerdefinierte Validierung „, damit Sie eine leere iban zur Verfügung stellen können, bic und Institut, das ist in Ordnung, aber wenn überhaupt. der Felder ist nicht leer, die oben genannten Constrait müssen halten "
Ich suche nach dem elegantesten Weg, dies zu erreichen.
Meine aktuelle Lösung ist - was ich irgendwie schmutzig denken, aber die Arbeit - eine @PrePersist Anweisung zu verwenden und Ausnahmen werfen von dort
@PrePersist
public void checkBankData() {
boolean ibanEmpty = iban == null || iban.isEmpty();
boolean ibanValid = !ibanEmpty && iban.length() >= 22 && iban.length() <= 34;
boolean bicEmpty = bic == null || bic.isEmpty();
boolean bicValid = !bicEmpty && bic.length() >= 8 && bic.length() <= 11;
boolean instituteEmpty = institute == null || institute.isEmpty();
boolean validState = (ibanEmpty && bicEmpty && instituteEmpty) || ibanValid && bicValid;
if (!validState) {
throw new IllegalStateException(
String.format(
"bank data is not empty and %s%s%s%s%s",
!ibanValid ? "iban has to be from 22 to 34 chars long" : "",
!ibanValid && !bicValid ? "and" : "",
!bicValid ? "bic has to be from 8 to 11 chars long" : "",
!ibanValid && !bicValid && instituteEmpty ? "and" : "",
instituteEmpty ? "institue must not be empty" : ""
)
);
}
}
, die nicht sinnvoll ist, Anmerkungen @Valid. Ein anderer Ansatz wäre die Definition eines benutzerdefinierten Validators wie hier beschrieben: http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html
Aber das sieht wirklich wie ein Overkill für meine Einschränkung aus.
Gibt es keinen anderen eleganten Weg?
Dank