Hibernation check for save (paste) only

We have a problem with deprecated code. For the "username" field, a validator is installed that checks its length and makes sure that it contains at least one letter:

@Column(name = "username")
@Size(min = 4, max = 40)
@Pattern(regexp = "^.*[a-zA-Z]+.*$")
private String username;

      

The problem is that some existing stale data does not match these checks, and I am trying to find a way to have these checks ignored for stale data (old users), but still apply to newly created users.

I was thinking about transferring the validation to a method setUsername(...)

(so the value will only be validated on actual change), but that threw an exception:

javax.validation.ValidationException: Annotated methods must follow the JavaBeans naming convention. setUsername() does not.

      

I also made sure that the object is relevant dynamicUpdate=true

, but that doesn't help as hibernate checks all properties even if no changes happened.

How can I prevent these checks for existing entities during upgrade?
I don't want the fix to affect other property checks on the same object, and I can't change the hibernate configuration.

+3


source to share


1 answer


After two days of research, I found out how to make this work.
 Obviously, specifying validations that would only be checked for INSERT

is not that difficult. The only changes that are required is to set these checks for a specific check group and check that group during INSERT

/ pre-persist

.

First of all, I created an interface called platform.persistence.InsertOnlyValidations

, which will be used as a group to be checked out in pre-check mode only.

Than, I added a group to the field validation username

:

@Column(name = "username")
@Size(min = 4, max = 40, groups = {InsertOnlyValidations.class})
@Pattern(regexp = "^.*[a-zA-Z]+.*$", groups = {InsertOnlyValidations.class})
private String username;

      



This indicates hibernation does not use these checks as part of the default group. Now I needed to instruct hibernate to test these validation rules at insert time.
The way to do this is very simple, I need to pass a property javax.persistence.validation.group.pre-persist

specifying which groups will be checked during the event pre-persist

:

javax.persistence.validation.group.pre-persist=javax.validation.groups.Default,platform.persistence.InsertOnlyValidations

      

This indicates hibernation, that during the event, pre-persist

all checks by default will be checked ( javax.validation.groups.Default

) in addition to all checks included in the group InsertOnlyValidations

.

+4


source







All Articles