Как создать собственный валидатор в список - PullRequest
0 голосов
/ 07 апреля 2020

Я создал валидатор, чтобы убедиться, что список содержит хотя бы 1 элемент. Я могу sh Я мог бы применить это ограничение к любому типу списка

Аннотация:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = { TamanhoMinimoListaVaziaValidator.class})
public @interface TamanhoMinimoLista { 
    String message() default "{ListaNaoPodeSerVazia}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    int tamanhoMinimo() default 1;
}

Валидатор:

public class TamanhoMinimoListaVaziaValidator implements ConstraintValidator<TamanhoMinimoLista, List<Object>> {
@SuppressWarnings("unused")
private int tamanhoMinimo;

@Override
public void initialize(TamanhoMinimoLista constraintAnnotation) {
    this.tamanhoMinimo = constraintAnnotation.tamanhoMinimo();

    ConstraintValidator.super.initialize(constraintAnnotation);
}

@Override
public boolean isValid(List<Object> value, ConstraintValidatorContext context) {
    return value.size()>0;
}

}

Использование:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "UsuarioPerfil", joinColumns = @JoinColumn(name = "usuario_id"), inverseJoinColumns = @JoinColumn(name = "perfil_id"))
@TamanhoMinimoLista(tamanhoMinimo=1)
public List<Perfil> getPerfis() {
    return perfis;
}

Ошибка:

«отметка времени»: «2020-04-07T11: 09: 33.618-0300», «статус»: 500, «ошибка»: «Внутренняя ошибка сервера», «сообщение»: «HV000030: не найден валидатор для ограничения« br.com.mundosabido.adm.validators.TamanhoMinimoLista », проверяющий тип« java .util.List ». Проверьте конфигурацию для« perfis » '"," trace ":" javax.validation.UnexpectedTypeException: HV000030: Не найден валидатор для ограничения' br.com.mundosabido.adm.validators.TamanhoMinimoLista ', проверяющий тип' java .util.List '. Проверьте конфигурацию для 'perfis' \ r \ n \ tat org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getExceptionForNullValidator (ConstraintTree. java: 108) \ r \ n \ tat org.hibernate.validator.internal.engine. constraintvalidation.ConstraintTree.getInitializedConstraintValidator (ConstraintTree java:. 140) \ г \ п \ tat org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints (SimpleConstraintTree. java: 55) \ r \ n \ tat org.hibernate.validator.internal.engine.constraintvalidints.ConstraintTree.validateConstraintTree.validate java: 73) \ r \ n \ tat org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint (MetaConstraint. java: 127) \ r \ n \ tat org.hibernate.validator.internal. metadata.core.MetaConstraint.validateConstraint (MetaConstraint. java: 120) \ r \ n \ tat org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint (ValidatorImpl. java: 552) \ r \ n tat org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement (ValidatorImpl. java: 515) \ r \ n \ tat org.hibernate.validator.internal.engine.ValidatorImpl. \ r \ n \ tat org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup (ValidatorImpl. java: 447) \ r \ n \ tat org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext (ValidatorImpl. java: 397) \ r \ n \ tat org.hibernate.validator.internal.engine.ValidatorImpl.validate (ValidatorImpl. java: ) \ r \ n \ tat org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate (BeanValidationEventListener. java: 116) \ r \ n \ tat org.hibernate.cfg.beanvalidation. : 80) \ r \ n \ tat org.hibernate.action.internal.EntityIdentityInsertAction.preInsert (EntityIdentityInsertAction. java: 203) \ r \ n \ tat org.hibernate.action.internal.EntityIdentityInsertAction.execute (EntityIdentityInsertAction. 1039 *: 78) \ r \ n \ tat org.hibernate.engine.spi.ActionQueue.execute (ActionQueue. java: 645) \ r \ n \ tat org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction (ActionQueue . java: 282) \ r \ n \ tat org.hibernate.engine.spi.ActionQueue.addInsertAction (ActionQueue. java: 263) \ r \ n \ tat org.hibernate.engine.spi.ActionQueue.addAction . (ActionQueue java: 317 ) \ r \ n \ tat org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction (AbstractSaveEventListener. java: 330) \ r \ n \ tat org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrRvent45 * : 287) \ r \ n \ tat org.hibernate.event. 1047 *: 123) \ r \ n \ tat org.hibernate. . java: 243) \ r \ n \ tat org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached (DefaultMergeEventListener. java: 318) \ r \ n \ tat org.hibernate.event.internal. DefaultMergeEventListener.onMerge (DefaultMergeEventListener. java: 172) \ r \ n \ tat org.hibernate.event.internal.DefaultMergeEventListener.onMerge (DefaultMergeEventListener. java: 70) \ r \ n \ tat org.hiber. service.internal.EventListenerGroupImpl.fireEventOnEachListener (EventListenerGroupImpl. java: 102) \ r \ n \ tat org.hibernate.internal.SessionImpl.fireMerge (SessionImpl. java: 783) \ r \ n \ tat org.hiber. internal.SessionImpl.merge (SessionImpl. java: 770) \ r \ n \ tat sun.reflect.GeneratedMethodAccessor122.invoke (неизвестный источник) \ r \ n \ tat sun.reflect.DelegatingMethodAccessorImpl.invoke * DelegatingMethodAccessor. : 43) \ r \ n \ tat java .lang.reflect.Method.invoke (Метод. java: 498) \ r \ n \ tat org.springframework.orm.jpa.ExtendedEntityManagerCreator $ ExtendedEntityManagerInvocationHandler.invoke (ExtendedEntority) . java: 368) \ r \ n \ tat com.sun.proxy. $ Proxy255.merge (неизвестный источник) \ r \ n \ tat sun.reflect.GeneratedMethodAccessor122.invoke (неизвестный источник) \ r \ n \ tat sun.reflect.DelegatingMethodAcce ssorImpl.invoke (DelegatingMethodAccessorImpl. java: 43) \ r \ n \ tat java .lang.reflect.Method.invoke (Метод. java: 498) \ r \ n \ tat org.springframework.orm. jpa.SharedEntityManagerCreator $ SharedEntityManagerInvocationHandler.invoke (SharedEntityManagerCreator. java: 314) \ r \ n \ tat com.sun.proxy. $ Proxy255.merge (неизвестный источник) \ r \ n \ tat org.springfraj. repository.support.SimpleJpaRepository.save (SimpleJpaRepository. java: 557). 1065 *: 43) \ r \ n \ tat java .lang.reflect.Method.invoke (Метод. java: 498) \ r \ n \ tat org.springframework.data.repository.core.support.RepositoryComposition $ RepositoryFragments.invoke (RepositoryComposition. java: 371) \ r \ n \ tat org.springframework.data.repository.core.support.RepositoryComposition.invoke (RepositoryComposition. java: 204) \ r \ n \ tat org .springframework.data.repository.core.support.RepositoryFactorySupport $ I mplementationMethodExecutionInterceptor.invoke (RepositoryFactorySupport. java: 657) \ r \ n \ tat org.springframework.aop.framework. repository.core.support.RepositoryFactorySupport $ QueryExecutorMethodInterceptor.doInvoke (RepositoryFactorySupport. java: 621) \ r \ n \ tat org.springframework.data.repository.core.support. 605) \ r \ n \ tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation. java: 186) \ r \ n \ tat org.springframework.data. проекция. *: 80) \ r \ n \ tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation. java: 186) \ r \ n \ tat org.springframework.transaction.interceptor.TransactionAsin Transke AspectSupport. java: 366) \ r \ n \ tat org.springframework.transaction.interceptor.TransactionInterceptor.invoke (TransactionInterceptor. java: 99) \ r \ n \ tat org.springframework.aop.framework.ReflectiveMethod. продолжить (ReflectiveMethodInvocation. java: 186) \ r \ n \ tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke (PersistenceExceptionTranslationInterceptor. java: 139) \ r \ n \ tat org.spring.frame. ReflectiveMethodInvocation. org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation. java: 186) \ r \ n \ tat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke 10вн. \ tat org.springframework.aop.framework. ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation. java: 186) \ r \ n \ tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke (JdkDynamicAopProxy. java: 212 \\ \\ \\\. $ Proxy279.save (Неизвестный источник) \ r \ n \ tat br.com.mundosabido.adm.seguranca.UsuarioService.create (UsuarioService. java: 114) \ r \ n \ tat br.com.mundosabido.adm. seguranca.UsuarioController.create (UsuarioController. java: 99). : 62) \ r \ n \ tat sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl. java: 43) \ r \ n \ tat java .lang.reflect.Method.invoke (Метод. java: 498 ) \ r \ n \ tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (InvocableHandlerMethod. java: 190) \ r \ n \ tat org.springframework.web.method.support. . java: 138) \ r \ n \ tat org.springframework.web.servlet. mvc .method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod. java: 106) \ r \ n \ tat org.springframework.web.servlet. mvc Метад. *: 879) \ r \ n \ tat org.springframework.web.servlet. mvc .method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter. java: 793) \ r \ n \ tat org.springframework.web. servlet. mvc .method.AbstractHandlerMethodAdapter.handle (AbstractHandlerMethodAdapter. java: 87) \ r \ n \ tat org.springframework.web.servlet.DispatcherServlet.doDispatch (DispatcherServlet. * 10) \ tat org.springframework.web.servlet.DispatcherServlet.doService (DispatcherServlet. java: 943) \ r \ n \ tat org.springframework.web.servlet.FrameworkServlet.processRequest (FrameworkServlet. java 100): 100 \ n \ tat org.springframework.web.servlet.FrameworkServlet.doPost (FrameworkServlet. java: 909) \ r \ n \ tat javax.servlet.http.HttpServlet.service (HttpServlet. java: 660) \ r \ n \ tat org.springframework.web.servlet.FrameworkServlet.service (FrameworkServlet. java: 883) \ r \ n \ tat javax.servlet.http.HttpServlet.service (HttpServlet. java: 741) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 231) \ r \ n \ tat org. apache .catalina.core. ApplicationFilterChain.doFilter (ApplicationFilterChain. java: 166) \ r \ n \ tat org. apache .tomcat.websocket.server.WsFilter.doFilter (WsFilter. java: 53) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java: 166): 166 \ n \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. java: 320) \ r \ n \ tat org.springframework.security.web.access.intercept.FilterSecurityInterceptor. java: 126) \ r \ n \ tat org.springframework.security.web.access.intercept.FilterSecurityIntercepto r.doFilter (FilterSecurityInterceptor. java: 90) \ r \ n \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. java: 334) \ r \ n \ tat org.springfrawork. security.web.access.ExceptionTranslationFilter.doFilter (ExceptionTranslationFilter. java: 118) \ r \ n \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. * 1125 \ n: 334) \ tat org.springframework.security.web.session. 334) \ r \ n \ tat org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter (AnonymousAuthenticationFilter. java: 111) \ r \ n \ tat org.springframework.security.web.FilterChainProha (VirtualFilterCilterFilterCilter). FilterChainProxy. java: 334) \ r \ n \ tat org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter. doFilter (SecurityContextHolderAwareRequestFilter. java: 158) \ r \ n \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. java: 334) \ r \ n \ tat.pr. web.savedrequest.RequestCacheAwareFilter.doFilter (RequestCacheAwareFilter. java: 63) \ r \ n \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. * \ r \ n \): org.springframework.security.web.authentication.logout.LogoutFilter.doFilter (LogoutFilter. java: 116) \ r \ n \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain. 334) \ r \ n \ tat org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter (HeaderWriterFilter. java: 92) \ r \ n \ tat org.springframework.security.web.header.HeaderWriterFilter.do HeaderWriterFilter. java: 77) \ r \ n \ tat org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter. java: 119) \ r \ n \ tat org.springframework.securi ty.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. java: 334) \ r \ n \ tat org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter (SecurityContextPersistence \ 105: * n: 105). \ tat org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter (FilterChainProxy. java: 334) \ r \ n \ tat org.springframework.security.web.context.request.asyn c .Inter. (WebAsyncManagerIntegrationFilter. java: 56) \ r \ n \ tat org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter. java: 119) \ r \ n \ tat org.springframework.Filter. $ VirtualFilterChain.doFilter (FilterChainProxy. java: 334) \ r \ n \ tat org.springframework.security.web.FilterChainProxy.doFilterInternal (FilterChainProxy. java: 215) \ r \ n \ tat org.springframe.work .web.FilterChainProxy.doFilter (FilterChainProxy. java: 178) \ r \ n \ tat org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate (DelegatingFil terProxy. java: 358) \ r \ n \ tat org.springframework.web.filter.DelegatingFilterProxy.doFilter (DelegatingFilterProxy. java: 271) \ r \ n \ tat org. apache .catalina.core. ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java: 166) \ r \ n \ tat org.springra web.filter.RequestContextFilter.doFilterInternal (RequestContextFilter. java: 100) \ r \ n \ tat org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter. java: 119 \ \ \ n). apache .catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java: 166): 166 \ n \ tat org.springframework.web.filter.FormContentFilter.doFilterInternal (FormContentFilter. java: 93) \ r \ n \ tat org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFileter *: 119). \ r \ n \ tat org. apache .catalina.core.Applicati onFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java: 166) \ r \ n \ tat org.springra boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal (WebMvcMetricsFilter. java: 109) \ r \ n \ tat org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequest * 11 119) rf. \ n \ tat org. apache .catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. *: 166) \ r \ n \ tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal (CharacterEncodingFilter. java: 201) \ r \ n \ tat org.springframework.web.filter.OncePerRequestFilterPerterFilter. java: 119) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core. ApplicationFilterChain. doFilter (ApplicationFilterChain. java: 166) \ r \ n \ tat br.com.mundosabido.adm.config.CorsFilter.doFilter (CorsFilter. java: 45) \ r \ n \ tat org. apache. catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain. java: 193) \ r \ n \ tat org. apache .catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java: 166) \ r \ n org. apache .catalina.core.StandardWrapperValve.invoke (StandardWrapperValve. java: 202) \ r \ n \ tat org. apache .catalina.core.StandardContextValve.invoke (StandardContextValve. java): 96 \ r \ n \ tat org. apache .catalina.authenticator.AuthenticatorBase.invoke (AuthenticatorBase. java: 541) \ r \ n \ tat org. apache .catalina.core.StandardHostValve.invoke (StandardHostValve. java: 139) \ r \ n \ tat org. apache .catalina.valves.ErrorReportValve.invoke (ErrorReportValve. java: 92) \ r \ n \ tat org. apache .catalina.core. StandardEngineValve.invoke (StandardEngineValve. java: 74) \ r \ n \ tat org. apache .catalina.connector.CoyoteAdapter.service (CoyoteAdapter. java: 343) \ r \ n \ tat org. apache .coyote.http11 .Http11Processor.service (Http11Processor. java: 367) \ r \ n \ tat org. apache .coyote.AbstractProcessorLight.process (AbstractProcessorLight. java: 65) \ r \ n \ tat org. apache .coyote.AbstractProtocol $ ConnectionHandler.process (AbstractProtocol. java: 868) \ r \ n \ tat org. apache .tomcat.util. net .NioEndpoint $ SocketProcessor.doRun (NioEndpoint. java: 1639 ) \ r \ n \ tat org. apache .tomcat.util. net .SocketProcessorBase.run (SocketProcessorBase. java: 49) \ r \ n \ tat java .util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor. java: 1149) \ r \ n \ tat java .util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor. java: 624) \ r \ n \ tat org. apache .tomcat .util.threads.TaskThread $ WrappingRunnable.run (TaskThread. java: 61) \ r \ n \ tat java .lang.Thread.run (Тема. java: 748) \ r \ n "," путь ":" / api / private / Usuario / create "}

как ее решить?

...