Reputation: 26904
I'm using Hibernate to persist data decoded from file inputs. Since one of our format is a variable-length format, I'd like to easily check for possible insertion errors in the entity before the transaction gets committed, so I can handle exceptions and take appropriate actions.
If I have an entity
@Entity
public class Entity {
@Column(...,length=20)
private String col1;
@Column(...,length=20)
private String col2;
@Column(...,length=40)
private String col3;
...
@Column(...,length=100)
private String col..N;
}
I'd like to detect if the String
I set as value of each column is compatible with its length, possibly without instrumenting Java code to validate each and every field against the max length.
Currently, I only get a SQL exception when transaction is committed (i.e. @Transactional
method returns) for the whole batch when only a single record is affected by a problem. Catching an exception when I Session.persist(entity)
would be appreciable.
Any ideas?
Upvotes: 1
Views: 87
Reputation: 24433
Since you already use Hibernate, have you considered Hibernate Validator? It would look something like this
@Size(max = 20)
@Column(...,length=20)
private String col1;
// and validation itself
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<Entity>> constraintViolations = validator.validate(entity);
Downside is that you would have to use another set of annotations beside @Column
, but on the other hand it offers much more options.
Another option is to use aspects and intercept every setter for String
fields on classes annotated with @Entity
. In the aspect you would get the @Column
annotation and compare the parameter length with configured lenght
attribute n the annotation.
Upvotes: 4
Reputation: 3209
You can use a custom Interceptor to trim the Strings as suggested here: Properly handling long data in Hibernate
or maybe using the Length annotation and a custom Length validator as suggested here: hibernate validator LengthValidator of truncated string
Upvotes: 0