-2

I'm getting a NullPointerException with this Java DAO:

public abstract class AbstractDAO<BEAN extends Serializable, 
                                  ID extends Serializable> 
                                  extends HibernateDaoSupport 
                                  implements IDAO<BEAN, ID> {
   private Class<BEAN> beanClass;
   public AbstractDAO() {
   }   
   public AbstractDAO(Class<BEAN> clazz) {
      beanClass = clazz;
   }

   /**
    * {@inheritDoc}
    */
   @Transactional
   public BEAN findById(ID id) {
      @SuppressWarnings("unchecked")
      BEAN instance = 
          (BEAN) getSessionFactory().getCurrentSession().get(beanClass, id);
      return instance;
   }
}
public class TestCaseDAO extends AbstractDAO<TestCase, Long> {
   public TestCaseDAO(Class<TestCase> clazz) {
      super(clazz);
   }
   public TestCaseDAO() {
   }
   @Override
   public void persist(TestCase transientInstance) {
   }
}

Exception I get:

Exception in thread "main" java.lang.NullPointerException

Can anyone please help me out?

4

1 回答 1

1

You are creating your TestCaseDAO bean without specifying a beanClass

<bean id="testCaseDAO" class="com.germin8.autom8.db.hb.dao.TestCaseDAO"
    parent="abstractDAO"></bean> 

Spring will use the no-arg constructor of TestCaseDAO which is empty.

When this code executes

BEAN instance =  (BEAN) getSessionFactory().getCurrentSession().get(beanClass, id);

beanClass is null. This throws a NullPointerException down the line.

Since you know that TestCaseDAO is for TestCase only, change to

public TestCaseDAO() {
    super(TestCase.class);
}

and get rid of your other constructor. Perform similar changes to your other AbstractDAO implementations.

于 2013-11-14T15:15:40.537 回答