当前位置: 首页 > 知识库问答 >
问题:

自定义约束验证调用isValid两次,抛出NullPointer异常

夏何平
2023-03-14

我创建了一个自定义约束验证器,用于检查用户名的验证,验证器正在访问数据库并检查记录是否已存在以及是否符合正则表达式。我收到相当奇怪的错误,因为如果用户名已经存在,验证器可以正常工作,但是当输入有效输入(不存在的用户名)时,它会抛出一个 NullPointerException。

我放置了一个计数器和一些语句来跟踪应用程序崩溃的位置,我将在堆栈跟踪中包括这些。应用程序似乎正在调用初始化isValid方法两次,第二次是抛出NullPointer。我已经看过这个问题,它说添加<code>

我在想也许我必须在其他地方禁用它,因为我没有使用我的持久性.xml来配置应用程序,而是使用 jpaContext.xml 文件。

如果有人对故障修复有任何建议/之前的经验/我应该在哪里寻找修复,我将非常感激。

自定义约束验证器

public class UserNameConstraintValidator implements ConstraintValidator<UserName, String> {
@Autowired
private HouseholdService householdService;

private int counter = 0;


public void initialize(UserName userName) {
    System.out.println("counter inside initialize is at count : " + counter);
}

public boolean isValid(String userName, ConstraintValidatorContext cxt) {
    System.out.println(userName);
    counter ++;
    System.out.println("counter is at count : " + counter);

    if(householdService.checkForUser(userName) || userName == null) {      //line 26
        System.out.println(userName);
        System.out.println("counter inside if statement is at count : " + counter);
        return false;
    }
    else {
        System.out.println(userName);
        System.out.println("counter inside else statement is at count : " + counter);
        return (userName.matches("^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$"));
    }
}
}

堆栈跟踪

        counter inside initialize is at count : 0
        newUser
        counter is at count : 1
        Tue Mar 28 19:18:23 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Mar 28, 2017 7:18:23 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
        INFO: HHH000397: Using ASTQueryTranslatorFactory
        Hibernate: select household0_.id as id1_1_, household0_.password as password2_1_, household0_.userName as userName3_1_ from Households household0_ where household0_.userName like ? limit ?
        Hibernate: select household0_.id as id1_1_, household0_.password as password2_1_, household0_.userName as userName3_1_ from Households household0_ where household0_.userName like ? limit ?
        inside HouseholdRepository, if statement has returned : 0
        newUser
        counter inside else statement is at count : 1
        Tue Mar 28 19:18:24 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Tue Mar 28 19:18:24 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Hibernate: select next_val as id_val from hibernate_sequence for update
        Hibernate: update hibernate_sequence set next_val= ? where next_val=?
        counter inside initialize is at count : 0
        newUser
        counter is at count : 1
        Mar 28, 2017 7:18:24 PM org.apache.catalina.core.StandardWrapperValve invoke
        SEVERE: Servlet.service() for servlet [springDispatcherServlet] in context with path [/Bill_Calculator] threw exception [Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.] with root cause
        java.lang.NullPointerException
            at com.chrishammer.view.UserNameConstraintValidator.isValid(UserNameConstraintValidator.java:26)
            at com.chrishammer.view.UserNameConstraintValidator.isValid(UserNameConstraintValidator.java:1)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:446)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:127)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
            at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:616)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:581)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:527)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:495)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:460)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:410)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:207)
            at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116)
            at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80)
            at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:205)
            at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:82)
            at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
            at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
            at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
            at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
            at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
            at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1414)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
            at com.sun.proxy.$Proxy36.flush(Unknown Source)
            at com.chrishammer.repository.HouseholdRepositoryImpl.save(HouseholdRepositoryImpl.java:23)
            at com.chrishammer.service.HouseholdServiceImpl.save(HouseholdServiceImpl.java:24)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
            at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
            at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
            at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
            at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
            at com.sun.proxy.$Proxy41.save(Unknown Source)
            at com.chrishammer.controller.CreateAccountController.submitUser(CreateAccountController.java:34)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
            at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
            at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
            at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
            at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
            at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
            at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:745)

坚持不懈.xml

<persistence    xmlns="http:://java.sun.com/xml/ns.persistence"
            xmlns:xsi="http:://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http:://java.sun.com/xml/ns.persistence 
                                http:://java.sun.com/xml/ns/persistence_2_0.xsd"
            version ="2.0" >


<persistence-unit name="punit">
    <property name="javax.persistence.validation.mode" value="none"/>
</persistence-unit>             



</persistence>

jpa上下文.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<context:annotation-config />
<context:component-scan base-package="com.chrishammer" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="punit" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name ="jpaPropertyMap">
        <map>
            <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <entry key="hibernate.hbm2ddl.auto" value="update" />
            <entry key="hivernate.format_sql" value="true" />
        </map>
    </property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/testingDb?autoReconnect=true" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>
</beans>

如果你还需要什么,请告诉我,任何帮助都将不胜感激。

共有1个答案

公冶兴文
2023-03-14

我已经解决了这个问题。在浏览这里找到的关于hibernate bean验证的文档时,我注意到< code >

 类似资料:
  • 我有以下验证器,用于验证更新请求。 object.getIdCreditor()有一个值,但是findById方法的执行["CreditorRepository.findById(object.getIdCreditor())" ] 进入NullPointer异常 我不明白怎么了。

  • 我有一个像下面这样的模型对象,带有自定义约束验证器。自定义验证器检查是否填充了fileName或小时。 有一种方法将此作为输入,它验证所有以下条件 > 条件不为空(通过默认验证器) criteria.id不为空(通过默认验证器) criteria.name不为空(通过默认验证器) 标准文件名或小时不为空(通过自定义验证器) 空评估(@NotNull@有效标准标准){} 现在,当我为这个模型类编写单

  • 我有一个自定义注释@UniqueModel,它由ConstraintValidator验证: 问题是,我需要在调用存储库的safe()-方法之前进行验证,否则字段注入将无法工作。 因此,我创建了一个带有@Valid注释的委托方法,以便在以下情况之前强制进行唯一验证: 不幸的是,这不起作用,似乎@Valid注释被Spring忽略了。 我如何确保验证的正确时间?

  • 我已经为此斗争了好几天,我已经阅读了这里的所有讨论,但没有解决方案...... 我有一个自定义约束… 独一无二.java 这是由UniqueConstraintValidator使用的.java 现在,我的模型有这个注释,我需要在其中验证字段的唯一性 现在,我知道自定义注释在更新现有对象时不起作用,但是现在我需要了解它是如何工作的。假设我们想要添加一个新对象。 当我试图保存一个已经存在的值时,我得

  • 问题内容: 我正在使用Spring MVC创建一个网站,并且为了持久性,我将Spring Data JPA与Hibernate 4用作我的JPA提供程序。目前正在使用Hibernate Validator处理验证。我有一个问题,我的验证程序被两次调用,我不知道为什么。这是一个问题的主要原因是因为第二轮未将依赖项自动关联到验证器中,并且出现了空指针异常。以下是导致失败的调用顺序: 提交注册表,然后首

  • null 有人能解释为什么要调用验证器两次,特别是为什么要跳过“userrepository.save(user);”回到这些验证器里? 多谢 下面是我的user.java类 我的用户存储库: 最后,我的persistence-context.xml文件