Make custom hibernate validation annotation for email existence

蓝咒 提交于 2020-01-04 05:35:41

问题


i was wondering if it's possible to make custom hibernate validation annotation that will check in the database if the email exist or not (call dao method and return true if the email exist)

so i can do something like:

    @NotBlank(message = "email is required")
@Email(message = "{invalid.email}")
    @EmailExist(message = "{email.exist}")
@Column(name = "email", length = 155, nullable = false)       
private String email;

please advise with a sample if possible, thanks in advance.


回答1:


Yes it should be possible, you just need to implement your custom annotation validator implementation.

If you use real AspectJ and annotate the class with @Configurable then you an use @Inject like in every other spring bean.

@See:

  • Spring Configurable: Spring Reference Chapter 7.8.1 Using AspectJ to dependency inject domain objects with Spring
  • JSR-000303 Bean Validation 1.0 Final Release Specification Chapter 2 Constraint Definition
  • Example of an custom Validation



回答2:


No need for AspectJ magic. If you are using spring, you just need to @Autowire -annotate your field, spring will inject the DAO. See Spring Reference 5.7.2.2 Configuring Custom Constraints:

By default, the LocalValidatorFactoryBean configures a SpringConstraintValidatorFactory that uses Spring to create ConstraintValidator instances. This allows your custom ConstraintValidators to benefit from dependency injection like any other Spring bean.

So your only job is to write the custom annotation. Easy to find samples on the web.



来源:https://stackoverflow.com/questions/8375704/make-custom-hibernate-validation-annotation-for-email-existence

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