1.如果你想在自己的main方法中做测试,那么不能用new Dao的这种形式
原因:当你getCurrentSession时,会抛出空指针,原因是通过new Dao这种形式,是无法注入applicationContext.xml中的dataSource和sessionFactory对象的,所以sessionFactory为空。
解决:通过getBean获取Dao的对象
2.如果再通过session执行语句的时候,抛出No Session found for current thread
原因:
SessionFactory的getCurrentSession并不能保证在没有当前Session的情况下会自动创建一个新的,这取决于CurrentSessionContext的实现,SessionFactory将调用CurrentSessionContext的currentSession()方法来获得Session。在Spring中,如果我们在没有配置TransactionManager并且没有事先调用SessionFactory.openSession()的情况直接调用getCurrentSession(),那么程序将抛出“No Session foundfor current thread”异常。
解决:利用AOP配置Transactional,并且通过@Transactional或者声明的方式配置的事务边界,那么Spring会在开始事务之前通过AOP的方式为当前线程创建Session,此时调用getCurrentSession()将得到正确结果。