Reputation: 91
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, i.e 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.
Upvotes: 0
Views: 526
Reputation: 136
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());
}
}
Upvotes: 1