After two days of research I found out how to make this work.
Apparently, specifying validations that would be validated on INSERT
only is not that difficult. The only changes required are to set these validations to a specific validation group and to validate this group during INSERT
/pre-persist
events.
First of all I created an interface called platform.persistence.InsertOnlyValidations
to be used as a group which will be validated during pre-persist only.
Than, I added the group to the username
field validations:
@Column(name = "username")
@Size(min = 4, max = 40, groups = {InsertOnlyValidations.class})
@Pattern(regexp = "^.*[a-zA-Z]+.*$", groups = {InsertOnlyValidations.class})
private String username;
This instructs hibernate not to use these validations as part of the default group. Now, I needed to instruct hibernate to validate these validation rules during insert only.
The way to do that is very simple, I needed to pass the property javax.persistence.validation.group.pre-persist
, while indicating which groups will be validated during a pre-persist
event:
javax.persistence.validation.group.pre-persist=javax.validation.groups.Default,platform.persistence.InsertOnlyValidations
This instructs hibernate that during a pre-persist
event all default validations will be validated (javax.validation.groups.Default
) in addition to all the validations included in the InsertOnlyValidations
group.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…