问答详情
源自:1-11 通过Hibernate API编写访问数据库的代码

求救!空指针异常java.lang.NullPointerException

ps:43行对应24行
错误:
java.lang.NullPointerException
	at StudentsTest.testSaveStudents(StudentsTest.java:43)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at junit.framework.TestCase.runTest(TestCase.java:168)
	at junit.framework.TestCase.runBare(TestCase.java:134)
	at junit.framework.TestResult$1.protect(TestResult.java:110)
	at junit.framework.TestResult.runProtected(TestResult.java:128)
	at junit.framework.TestResult.run(TestResult.java:113)
	at junit.framework.TestCase.run(TestCase.java:124)
	at junit.framework.TestSuite.runTest(TestSuite.java:243)
	at junit.framework.TestSuite.run(TestSuite.java:238)
	at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

http://img2.mukewang.com/5a1ac0d6000198bb04420454.jpg

@Before
	public void init(){
		Configuration config=new Configuration().configure();
		
		ServiceRegistry serviceRegisty=new StandardServiceRegistryBuilder()
				.applySettings(config.getProperties()).build();
		
		sessionFactory=new MetadataSources(serviceRegisty).buildMetadata().buildSessionFactory();
		
		session=sessionFactory.openSession();
		transaction=session.beginTransaction();
	}
	
	@After
	public void destory(){
		transaction.commit();
		session.close();
		sessionFactory.close();
	}
	
	@Test
	public void testSaveStudents(){
		Students s=new Students(1,"男","张师傅",new Date(),"武当山");
		session.save(s);
	}

http://img4.mukewang.com/5a1ac111000166c009540247.jpg

提问者:机智的意竹竹 2017-11-26 21:27

个回答

  • 慕田峪3481485
    2017-11-27 18:51:52

    用下面的方法创建 sessionFactory 对象吧;好像是版本有更新,空指针异常可能是其他方面导致的

    Configuration cfg = new Configuration().configure();  

    ServiceRegistry  builder=  (ServiceRegistry) new StandardServiceRegistryBuilde().                                                                    applySettings(cfg.getProperties()).build(); 

       sessionFactory = cfg.buildSessionFactory(builder);