Hibernate validations on save (insert) only

后端 未结 1 1107
礼貌的吻别
礼貌的吻别 2020-12-11 19:58

We encountered a problem with legacy code. There is a validation set for a \"username\" field, validating its length and making sure it contains at least one letter:

相关标签:
1条回答
  • 2020-12-11 20:29

    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.

    0 讨论(0)
提交回复
热议问题