2014-06-15 28 views
1

我正在實施GenericDao。我有兩個方法的問題 - getAll()和getById(Long id),實體類具有空值。看起來班級沒有設置。我怎麼解決這個問題 ?GenericDao,類<T>爲空

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

回答

2

您必須設置的PersonDaoclazz財產。這可以通過使用@PostConstruct註釋聲明post initialization callback來完成。

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

     @PostConstruct 
     public void init(){ 
     super.setClazz(Person.class); 
     } 
} 
+0

它的工作,謝謝 – kxyz

+0

@kxyz很高興我可以幫助! –