我明白了:
java.lang.StackOverflowError at kamienica.dao.ApartmentDaoImpl.findById(ApartmentDaoImpl.java:52)at at kamienica.dao.ApartmentDaoImpl.findById(ApartmentDaoImpl.java:52)at at kamienica.dao.ApartmentDaoImpl.findById(ApartmentDaoImpl.java:52) (依此类推......)
尝试通过它的主键获取对象时。
这是AbstractDAO:
public abstract class AbstractDao<PK extends Serializable, T> {
private final Class<T> persistentClass;
@SuppressWarnings("unchecked")
public AbstractDao() {
this.persistentClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[1];
}
@Autowired
private SessionFactory sessionFactory;
protected SessionFactory getSessionFactory() {
return sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public T findByPK(PK id) {
Session session = getSession();
T out = (T) session.load(persistentClass, id);
session.close();
return out;
}
以下是ApartmentDAO实施:
@Repository("apatmentDao")
public class ApartmentDaoImpl extends AbstractDao<Integer, Apartment> implements ApartmentDao {
public void save(Apartment apatment) {
persist(apatment);
}
@Override
@SuppressWarnings("unchecked")
public List<Apartment> getList() {
Criteria criteria = createEntityCriteria();
criteria.addOrder(Order.asc("apartmentNumber"));
return (List<Apartment>) criteria.list();
}
@Override
public void deleteByID(int id) {
Query query = getSession().createSQLQuery("delete from Apartment where id = :id");
query.setInteger("id", id);
query.executeUpdate();
}
@Override
public void update(Apartment apatment) {
update(apatment);
}
@Override
public Apartment findById(int id) {
// If I put System.out.println(id) here it will print id
// number until the stack overflow
Apartment ap = findById(id);
return ap;
}
我不知道造成这个问题的原因。其他方法工作得很好......
答案 0 :(得分:1)
您递归调用findById
方法。
@Override
public Apartment findById(int id) {
// Here you're recursively calling findById
Apartment ap = findById(id);
return ap;
}
我想你可以这样做,
@Override
public Apartment findById(int id) {
return findByPK(new Integer(id));
}
希望这有帮助。