Hibernate validations on save (insert) only

混江龙づ霸主 提交于 2019-11-29 14:31:25

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!