rohi rohi - 7 months ago 66
Java Question

Creating BaseDAO for Each Dao class

I created a spring application where i decided to add a BaseDAO to eliminate redundant create,
update,delete,findByid,and findAll methods for every dao. So i created a baseDao and every dao should extend this BaseDAO.

BaseDaoImpl



public class BaseDAOImpl implements BaseDAO{

SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}

@Override
public void create(ModelBase modelBase) {

Session session = this.sessionFactory.getCurrentSession();
session.persist(modelBase);
}

@Override
public void update(ModelBase modelBase) {

Session session = this.sessionFactory.getCurrentSession();
session.update(modelBase);
}

@Override
public Collection findAll(Class aClass) {

Session session = this.sessionFactory.getCurrentSession();
Collection modelCols = session.createQuery("from "+aClass.getSimpleName()).list();
return modelCols;
}

@Override
public ModelBase findById(Class aClass, Integer id) {
Session session = this.sessionFactory.getCurrentSession();
ModelBase modelBase = (ModelBase) session.load(aClass, new Integer(id));
return modelBase;
}



}


Then i extends this Dao to each DAO

EmployeeDAOImp



public class EmployeeDAOImpl extends BaseDAOImpl implements EmployeeDAO{

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
}


I created a BaseService like this. But when i try to access BaseDAO methods from EmployeeDAO it returns null pointer exception.
Why this happen. I dont want to use genericDAO from google. Because we should create DAOs
for each model. I want to eliminate this. So I follow this method.

Answer

Your are overriding setSessionFactory from base class for no reason, its already available with extending class EmployeeDAOImpl , either remove it or try below:

public class EmployeeDAOImpl extends BaseDAOImpl implements EmployeeDAO{

   //this reference should be from base class,
   // the extending class ref is hiding base ref.
  //  private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
      super.setSessionFactory(sf);
    }
}
Comments