【问题标题】:GenericDao, Class<T> is nullGenericDao,Class<T> 为空
【发布时间】:2014-06-15 11:40:50
【问题描述】:

我正在实施 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();
  }
 }

人道

    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);
}
}

【问题讨论】:

    标签: java spring hibernate generics dao


    【解决方案1】:

    您必须设置PersonDaoclazz 属性。这可以通过使用 @PostConstruct 注释声明 post initialization callback 来完成。

     @Repository("PersonDAO")
     public class PersonDaoImpl extends GenericDaoImpl<Person> implements PersonDao {
    
          @PostConstruct
          public void init(){
             super.setClazz(Person.class);
          }
     }
    

    【讨论】:

    • @kxyz 很高兴我能帮上忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多