Hibernate java.lang.NullPointerException

时间:2016-09-28 08:46:18

标签: java hibernate spring-mvc

我已将Set设置为我的实体。这是我的代码:

MyClassA:

@Entity
@Table(name = "aaa")
public class MyClassA {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @NotEmpty
    @Size(min = 3, max = 255)
    @Column(name = "name", nullable = false)
    private String name;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<MyClassB> mycollection = new HashSet<MyClassB>();

    public MyClassA() {    
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<MyClassB> getMyClassB() {
        return mycollection;
    }

    public void setMyClassB(Set<MyClassB> mycollection) {
        this.mycollection = mycollection;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((mycollection == null) ? 0 : mycollection.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MyClassA other = (MyClassA) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (mycollection == null) {
            if (other.mycollection != null)
                return false;
        } else if (!mycollection.equals(other.mycollection))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "MyClassA [id=" + id + ", name=" + name + ", mycollection=" + mycollection + "]";
    }       
}

MyClassB:

@Entity
@Table(name = "bbb")
public class MyClassB {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @NotEmpty
    @Size(min = 3, max = 255)
    @Column(name = "name", nullable = false)
    private String name;

    @NotEmpty
    @Size(min = 3, max = 255)
    @Column(name = "elementname", nullable = false)
    private String elementname;                

    @NotEmpty
    @Size(min = 3, max = 255)
    @Column(name = "type", nullable = false)
    private String type;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<MyClassC> mycollection = new HashSet<MyClassC>();

    public MyClassB() {    
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getElementname() {
        return elementname;
    }

    public void setElementname(String elementname) {
        this.elementname = elementname;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Set<MyClassC> getMyCollection() {
        return mycollection;
    }

    public void setMyCollection(Set<MyClassC> mycollection) {
        this.mycollection = mycollection;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((elementname == null) ? 0 : elementname.hashCode());
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
Line 79---> result = prime * result + ((mycollection == null) ? 0 : mycollection.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MyClassB other = (MyClassB) obj;
        if (elementname == null) {
            if (other.elementname != null)
                return false;
        } else if (!elementname.equals(other.elementname))
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (mycollection == null) {
            if (other.mycollection != null)
                return false;
        } else if (!mycollection.equals(other.mycollection))
            return false;
        if (type == null) {
            if (other.type != null)
                return false;
        } else if (!type.equals(other.type))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "MyClassB [id=" + id + ", name=" + name + ", elementname=" + elementname + ", type=" + type + ", mycollection=" + mycollection + "]";
    }       
}

MyClassC:

@Entity
@Table(name = "ccc")
public class MyClassC {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @NotEmpty
    @Size(min = 3, max = 255)
    @Column(name = "name", nullable = false)
    private String name;

    @NotEmpty
    @Size(min = 3, max = 255)
    @Column(name = "value", nullable = false)
    private String value;

    public MyClassC(){          
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MyClassC other = (MyClassC) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "MyClassC [id=" + id + ", name=" + name + ", value=" + value + "]";
    }

}

当我试图获取所有MyClassA对象时,在我的控制器中,我得到以下异常:

  

2016-09-28 10:10:46 DEBUG DefaultHandlerExceptionResolver:134 - 解决处理程序中的异常[public org.springframework.http.ResponseEntity&gt; com.example.controller.MyController.listAllMyClassA()]:java.lang.NullPointerException   2016-09-28 10:10:46 DEBUG DispatcherServlet:989 - 无法完成请求   显示java.lang.NullPointerException           at org.hibernate.engine.internal.StatefulPersistenceContext.getLoadedCollectionOwnerOrNull(StatefulPersistenceContext.java:756)           at org.hibernate.event.spi.AbstractCollectionEvent.getLoadedOwnerOrNull(AbstractCollectionEvent.java:75)           在org.hibernate.event.spi.InitializeCollectionEvent。(InitializeCollectionEvent.java:36)           在org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1931)           在org.hibernate.collection.internal.AbstractPersistentCollection $ 4.doWork(AbstractPersistentCollection.java:559)           at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:261)           at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:555)           在org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:143)           at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:316)           at com.example.model.MyClassB.hashCode(MyClassB.java:79)           在java.util.HashMap.hash(HashMap.java:338)           在java.util.HashMap.put(HashMap.java:611)           在java.util.HashSet.add(HashSet.java:219)           at java.util.AbstractCollection.addAll(AbstractCollection.java:344)           at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:344)           at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:251)           at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:238)           at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:211)           在org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1157)           在org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1126)           在org.hibernate.loader.Loader.processResultSet(Loader.java:973)           在org.hibernate.loader.Loader.doQuery(Loader.java:921)           在org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)           在org.hibernate.loader.Loader.doList(Loader.java:2554)           在org.hibernate.loader.Loader.doList(Loader.java:2540)           在org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)           在org.hibernate.loader.Loader.list(Loader.java:2365)           在org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)           在org.hibernate.internal.SessionImpl.list(SessionImpl.java:1718)           在org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)           在com.example.dao.MyClassADaoImpl.findAllGroupQuestions(MyClassADaoImpl.java:42)           在com.example.service.MyClassAImpl.findAllGroupQuestions(MyClassAImpl.java:41)           at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)           at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)           at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)           在java.lang.reflect.Method.invoke(Method.java:497)           在org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)           在org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)           在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:281)           at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)           在org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)           在org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)           在com.sun.proxy。$ Proxy63.findAllGroupQuestions(未知来源)           at gr.citystore.helios.controller.QuestionaireController.listAllGroupQuestions(QuestionaireController.java:212)           at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)           at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)           at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)           在java.lang.reflect.Method.invoke(Method.java:497)           在org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)           在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)           在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)           在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)           在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)           在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)           在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)           在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)           在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)           在org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)           在javax.servlet.http.HttpServlet.service(HttpServlet.java:622)           在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)           在javax.servlet.http.HttpServlet.service(HttpServlet.java:729)           在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)           在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)           在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)           在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)           在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:316)           在org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)           在org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:168)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:96)           在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)           在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)           在org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)           在org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330)           在org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)           在org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)           在org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)           在org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)           在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)           在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)           在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)           在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)           在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)           at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)           at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)           在org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)           在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)           在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)           在org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)           at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:674)           在org.apache.tomcat.util.net.AprEndpoint $ SocketProcessor.doRun(AprEndpoint.java:2500)           在org.apache.tomcat.util.net.AprEndpoint $ SocketProcessor.run(AprEndpoint.java:2489)           在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)           在java.lang.Thread.run(Thread.java:745)

MyClassADaoImpl:

@SuppressWarnings("unchecked")
public List<MyClassA> findAllMyClassAs() {
    Criteria criteria = createEntityCriteria();
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return (List<MyClassA>) criteria.list();
}

最后,我的服务实现MyClassAImpl:

public List<MyClassA> findAllMyClassAs() {
        return dao.findAllMyClassAs();
    }

我的Hibernate版本是4.3.11.Final。如果您需要任何其他信息,请告诉我们!感谢

1 个答案:

答案 0 :(得分:4)

查看你的stacktrace,我相信这个问题的根源在你的hashCode方法中:

  

com.example.model.MyClassB.hashCode(MyClassB.java:79)

尝试从hashCode方法中删除sets属性。我不认为这是计算类的哈希值所必需的。在大多数情况下,您使用业务键(即标识对象的唯一属性)。

https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html

安全! :)