Joe Essey
Joe Essey

Reputation: 3527

How to validate on some persistence actions, but not others

I've got a requirement that states a user can 'save' a foo with no validation at all, but if they 'submit' then the object must be validated. I've got this all built and working on the front-end with Parsley.js, but want to add back-end validation.

What is the typical approach to doing this with Spring/Boot? I understand the basic JPA validation, but I don't know how to apply it conditionally.

I want to also mention I tried to do this with 2 subclasses of Foo, but I'm unable to manage switching types, either because it's not possible in Java, or because I don't understand how you can instantiate a new version of the object and expect it to .equals() the old version for Hibernate persistence.

Thanks for any insight.

Upvotes: 1

Views: 91

Answers (2)

Tobias Liefke
Tobias Liefke

Reputation: 9022

JPA has no possibility for conditional validations.

Why? Because many validations are just database constraints that are not validated by JPA, but unconditionally by the database.

For example a

@NotNull
private Integer value;

will create a column with a NOT NULL constraint.

Or a

@Size(max = 100)
private String value;

will create a column of VARCHAR(100)

As you might understand it is not possible to save a value into such a column that breaks the size constraint and has more than 100 characters.

And indeed - it is not possible to switch the type of an object in Java.

You can cast for example a Entity1 to Entity2, but that is only the variable for the compiler. The object itself is an Entity1 - no matter what you try. But you can copy all values from an instance of Entity1 to a new instance of Entity2:

Entity1 entity1 = ...
Entity2 entity2 = new Entity2();
entity2.setProperty(entity1.getProperty());
...
entityManager.persist(entity2);
entityManager.delete(entity1);

If you don't like to copy all the properties by hand, you could use BeanUtils.copyProperties from Apache BeanUtils.

Upvotes: 0

Neil McGuigan
Neil McGuigan

Reputation: 48256

  1. Use JSR 303 Validation Groups. This gives you conditional validation.

  2. Use Spring's @Validated in your handler methods. This lets you apply different validations in your Controllers

  3. Follow my example here: http://blog.databasepatterns.com/2014/06/draft-entities-hibernate-validator.html

Upvotes: 1

Related Questions