我嵌套設置爲我的實體。這裏是我的代碼:Hibernate java.lang.NullPointerException
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年9月28日10時10分46秒DEBUG DefaultHandlerExceptionResolver:134 - 從處理程序解決的異常[ public org.springframework.http.ResponseEntity> 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) 在org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:261) 在org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection .java:555) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:143) at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:316) (HashMap.java:611) at com.example.model.MyClassB.hashCode(MyClassB.java:79) at java.util.HashMap.hash(HashMap.java:338) at java.util.HashMap.put(HashMap.java:611)在java.util.HashSet.add(HashSet.java:219) (位於java.util.AbstractCollection.addAll(AbstractCollection.java:344) at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java: 344) 在org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:251) 在org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:238) 在有機hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:211)org.hibernate.loader.Loader.processResultSet(Loader。org.hibernate.loader.Loader.java:1157) at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1126) at org.hibernate.loader.Loader.processResultSet(Loader。 java:973) at org.hibernate.loader.Loader.doQuery(Loader.java:921) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355) at org.hibernate.loader.Loader。 doList(Loader.java:2554) at org.hibernate.loader.Loader.doList(Loader.java:2540) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader。java:2370) at org.hibernate.loader.Loader.list(Loader.java:2365) at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126) at org.hibernate.internal。 SessionImpl.list(SessionImpl.java:1718) at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380) at com.example.dao.MyClassADaoImpl.findAllGroupQuestions(MyClassADaoImpl.java:42) at com。 example.service.MyClassAImpl.findAllGroupQuestions(MyClassAImpl.java:41) 在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法) 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在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) 在org.springframework.transaction.interceptor.TransactionInterceptor $ 1.proceedWithInvocation(TransactionInterceptor.java:99) 在org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) 在org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) 在org.spring framework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy。$ Proxy63.findAllGroupQuestions(Unknown源) 在gr.citystore.helios.controller.QuestionaireController.listAllGroupQuestions(QuestionaireController.java:212) 在sun.reflect.NativeMethodAccessorImpl.invoke0(本機方法) 在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62 ) 在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.lang.reflect.Method.invoke(Method.java:497) 在org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (Invoc ableHandlerMethod.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) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet。在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter( ApplicationFilterChain.java:206) at org.apache.tomcat。websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at 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) 的組織。 springframework.security.web.access.ExceptionTr org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:330) at 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) at 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( FilterChainPro xy.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) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) at 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) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) at 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。 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) at 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) at 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。如果您需要其他信息,請告訴我!在您的堆棧跟蹤感謝
你能指出哪一行是你的代碼片段中的MyClassB.java中的第79行嗎?這也將幫助我們給出一個更具體的答案,爲什麼無論是否爲null,儘管存在非空的註釋(這是爲什麼,現在,我不把它標記爲http:// stackoverflow的重複項。 COM /問題/ 218384 /什麼 - 是 - 一 - NullPointerException異常和知識-DO-I-FIX-IT)。 –
@JasonC,我已經在hashCode方法中編輯了MyClassB,指出哪一行是79. – KostasC
[使用Hibernate時要小心比較'Class'和'=='](http://blog.xebia。com/advanced-hibernate-proxy-pitfalls /),如果啓用延遲加載,Hibernate可以生成代理類並返回那些實例,而不是實際的類。例如,與在線訪問相同的處理'equals'和'hashCode';考慮改用getter;這可能是也可能不是問題的真正根源。考慮爲哈希和比較實現創建單元測試,包括從數據庫查詢的對象和手動構建的對象,以驗證您的設置是否按預期工作。 –