Hibernate的泛型我何时应该使用标准?

时间:2016-10-10 05:42:59

标签: java spring hibernate generics dao

我尝试在代码中使用泛型。 我有Dao从BD获取信息:

@Component
public class BasicDAOImpl<T> implements BasicDAO<T> {
    private Class<T> type;

    public BasicDAOImpl(Class<T> type) {this.type = type;
    }

    public BasicDAOImpl() {
    }

    @Autowired
    SessionFactory sessionfactory;

    @Override
    @Transactional
    public List<T> getAllByKey(int id) {
        List<T> list = new ArrayList<>();
        try{
            Session session = sessionfactory.getCurrentSession();
            Criteria criteria = session.createCriteria(type);
            criteria.add(Restrictions.eq("parentid", id));
           list.addAll(criteria.list());
        }catch (HibernateException e){}

        return list;
    }

我有:  WorkoutDAOImpl扩展了BasicDAOImpl

public class WorkoutDAOImpl extends BasicDAOImpl<Workout> implements WorkoutDAO {}

豆:

@Bean
public WorkoutDAO workoutDAO(){
    return new WorkoutDAOImpl();
}

我在我的代码中写道:

workoutDAO.getAllByKey(int 2)

并收到错误

java.lang.NullPointerException

Criteria criteria = session.createCriteria(type)

为什么呢? 如果写Criteria criteria = session.createCriteria(Workout.class),则不会出现任何错误。

PS /抱歉或我的英文:)

2 个答案:

答案 0 :(得分:0)

Workout.class未从BasicDAOImpl传递给WorkoutDAOImpl,因此Class<T> type未初始化,您获得NullPointerException。添加无参数构造函数:

public class WorkoutDAOImpl extends BasicDAOImpl<Workout> implements WorkoutDAO {

    public WorkoutDAOImpl() {
        super(Workout.class);
    }
}

答案 1 :(得分:0)

您需要调用 BasicDAOImpl 类的一个参数构造函数,以便初始化类型变量。

  1. WorkoutDAOImpl 类中创建无参数构造函数,并调用Super Class Constructor,即 BasicDAOImpl ,如下所示:
  2. public class WorkoutDAOImpl extends BasicDAOImpl implements WorkoutDAO {
          WorkoutDAOImpl(){
           super(Workout.class);
          }
    
        }
    

    虽然,您也可以使用Reflection来解决它。但是,按照您想要的方式,您必须显式调用BasicDAOImpl的构造函数。