GenericDao,Class <t>为空</t>

时间:2014-06-15 11:40:51

标签: java spring hibernate generics dao

我正在实施GenericDao。我有2个方法的问题 - getAll()和getById(Long id),实体类有空值。看起来这个类没有设置。我怎么解决这个问题 ?

 @Repository
 public class GenericDaoImpl<T> implements GenericDao<T> {

private Class<T> clazz;

@Autowired
SessionFactory sessionFactory;

public void setClazz(final Class<T> clazzToSet) {
    this.clazz = clazzToSet;
}

public T getById(final Long id) {
    return (T) this.getCurrentSession().get(this.clazz, id);
}

public List<T> getAll() {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
            this.clazz);
    return criteria.list();

}
   protected final Session getCurrentSession() {
    return this.sessionFactory.getCurrentSession();
  }
 }

PersonDao

    public interface PersonDao extends GenericDao<Person> { }

PersonDaoImpl

 @Repository("PersonDAO")
 public class PersonDaoImpl extends GenericDaoImpl<Person> implements PersonDao {}

服务:

@Service
public class PersonServiceImpl implements PersonService {

   @Autowired
  private PersonDao personDao;


@Transactional
public List<Person> getAll() {

    return personDao.getAll();
}


@Transactional
public Person getById(Long id) {
    return personDao.getById(id);
}
}

1 个答案:

答案 0 :(得分:2)

您必须设置clazz的{​​{1}}属性。这可以通过使用PersonDao注释声明post initialization callback来完成。

@PostConstruct