简体   繁体   中英

SEAM and Hibernate validation

Seam 2, Jboss 6.1

I currently use Hibernate validation annotations on my persistance object with seam to do validation on my jsf pages:

@Entity
@Table(name = "CLIENT", catalog = "testdb")
public class Client implements java.io.Serializable {

private Integer             id;
private String              name;

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

@Column(name = "NAME", unique = true, nullable = false, length = 64)
@org.hibernate.validator.Length(min=4,max=64)
public String getName() {
    return this.name;
}

...Setters and rest
}

This works perfectly and when the name field length is less than 4 characters a nice error is displayed.

The problem is users submit data in other channels, ie spreadsheet imports, 3de party applications, etc. Thus I have to do the validation in my java code as follow:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<K>> constraintViolations = validator.validate(bean);

Now this does not pick up any validation errors, but persisting the data does throw exception so it does work somewhere down the line. I can get it to work by using @org.hibernate.validator.constraints.Length but then the jsf screen does not report the constraint problems.

I looks to me like the @org.hibernate.validator.Length is a old legacy Hibernate Validator library but this is very entangle into seam 2 so can not be removed.

Anyone know how to do validation using the legacy hibernate annotations in java code.

No need to manually call hibernate validation. Handle errors at save

    try {
        save();
    } catch (InvalidStateException e) {
        logHibernateValidationException(e);
        ...

private void logHibernateValidationException(InvalidStateException e) {
    for (InvalidValue invalidValue : e.getInvalidValues()) {
        LOGGER.warn("Validation Failed. Instance of bean class: {0} has an invalid property: {1} with message: {2}",
                invalidValue.getBeanClass().getSimpleName(),
                invalidValue.getPropertyName(),
                invalidValue.getMessage());
    }
}

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