13.2. バリデーション制約
13.2.3. Jakarta Bean Validation カスタム制約の使用
Jakarta Bean Validation API は、@NotNull や @Size などの標準の制約アノテーションのセットを定義 します。しかし、これらの事前定義された制約が十分でない場合、バリデーションの要件に合ったカス タム制約を簡単に作成できます。
Jakarta Bean Validation を作成する場合、カスタム制約には制約アノテーションの作成と制約バリ
データーの実装が必要になります。以下のコードサンプルは、JBoss EAP に同梱される
bean-validation-custom-constraint クイックスタートから抜粋したものです。完全な作業例はこのクイック スタートを参照してください。
13.2.3.1.
制約アノテーションの作成 制約アノテーションの作成
以下は、AddressValidator クラスで定義されたカスタム制約のセットを使用して、エンティティー
Person の personAddress フィールドがバリデーションされる例を表しています。
1. エンティティー Person を作成します。
例
例
: Personクラス クラス
package org.jboss.as.quickstarts.bean_validation_custom_constraint;
@Entity
@Table(name = "person")
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
2. 制約バリデーターファイルを作成します。
例
例
: Addressインターフェース インターフェース
@Column(name = "person_id") private Long personId;@NotNull @Size(min = 4)
private String firstName;
@NotNull @Size(min = 4)
private String lastName;
// Custom Constraint @Address for bean validation @NotNull
@Address
@OneToOne(mappedBy = "person", cascade = CascadeType.ALL) private PersonAddress personAddress;
public Person() { }
public Person(String firstName, String lastName, PersonAddress address) { this.firstName = firstName;
this.lastName = lastName;
this.personAddress = address;
}
/* getters and setters omitted for brevity*/
}
package org.jboss.as.quickstarts.bean_validation_custom_constraint;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
// Linking the AddressValidator class with @Address annotation.
@Constraint(validatedBy = { AddressValidator.class })
// This constraint annotation can be used only on fields and method parameters.
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface Address {
// The message to return when the instance of MyAddress fails the validation.
String message() default "Address Fields must not be null/empty and obey character limit constraints";
例
例
: PersonAddressクラス クラス
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
package org.jboss.as.quickstarts.bean_validation_custom_constraint;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
@Entity
@Table(name = "person_address")
public class PersonAddress implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "person_id", unique = true, nullable = false) @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long personId;
private String streetAddress;
private String locality;
private String city;
private String state;
private String country;
private String pinCode;
@OneToOne
@PrimaryKeyJoinColumn private Person person;
public PersonAddress() { }
public PersonAddress(String streetAddress, String locality, String city, String state, String country, String pinCode) {
this.streetAddress = streetAddress;
this.locality = locality;
this.city = city;
this.state = state;
this.country = country;
this.pinCode = pinCode;
}
13.2.3.2.
制約バリデーターの実装 制約バリデーターの実装
アノテーションを定義したら、@Address アノテーションが付けられた要素のバリデーションが可能な 制約バリデーターを作成する必要があります。これには、以下のように ConstraintValidator インター フェースを実装します。
例
例
: AddressValidatorクラス クラス
/* getters and setters omitted for brevity*/
}
package org.jboss.as.quickstarts.bean_validation_custom_constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.jboss.as.quickstarts.bean_validation_custom_constraint.PersonAddress;
public class AddressValidator implements ConstraintValidator<Address, PersonAddress> { public void initialize(Address constraintAnnotation) {
} /**
* 1. A null address is handled by the @NotNull constraint on the @Address.
* 2. The address should have all the data values specified.
* 3. Pin code in the address should be of at least 6 characters.
* 4. The country in the address should be of at least 4 characters.
*/
public boolean isValid(PersonAddress value, ConstraintValidatorContext context) { if (value == null) {
return true;
}
if (value.getCity() == null || value.getCountry() == null || value.getLocality() == null
|| value.getPinCode() == null || value.getState() == null || value.getStreetAddress() == null) { return false;
}
if (value.getCity().isEmpty()
|| value.getCountry().isEmpty() || value.getLocality().isEmpty() || value.getPinCode().isEmpty() || value.getState().isEmpty() ||
value.getStreetAddress().isEmpty()) { return false;
}
if (value.getPinCode().length() < 6) { return false;
}
if (value.getCountry().length() < 4) { return false;
}