1. 程式人生 > >報錯:Spring整合Hibernate java.lang.NullPointerException

報錯:Spring整合Hibernate java.lang.NullPointerException

Exception in thread "main" java.lang.NullPointerException
at com.ye.service.impl.AddressServiceImpl.addAddress(AddressServiceImpl.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy9.addAddress(Unknown Source)
at com.ye.test.AddressTest.add(AddressTest.java:38)

at com.ye.test.AddressTest.main(AddressTest.java:27)

原因:持久化類使用了關聯屬性,但是測試中沒被關聯的屬性。

程式碼:

public static void addAccout(){
		User user=hibernateDAO.findUserById(1);
		Accout accout1=new Accout();
		accout1.setActNo("123");
		accout1.setBal(2000.0);
		accout1.setUser(user);
		hibernateDAO.addAccout(accout1);
		Accout accout2=new Accout();
		accout2.setActNo("456");
		accout2.setBal(3000.0);
		//設定單向多對一關聯關係
		accout2.setUser(user);
		hibernateDAO.addAccout(accout2);
	}
如果將上面程式碼中的hibernateDAO.addAccout(accout1);刪除,就會報錯。