gpt4 book ai didi

java - Spring Hibernate,尝试获取实体时堆栈溢出

转载 作者:行者123 更新时间:2023-11-30 07:43:20 27 4
gpt4 key购买 nike

我得到:

java.lang.StackOverflowError at kamienica.dao.ApartmentDaoImpl.findById(ApartmentDaoImpl.java:52) at kamienica.dao.ApartmentDaoImpl.findById(ApartmentDaoImpl.java:52) at kamienica.dao.ApartmentDaoImpl.findById(ApartmentDaoImpl.java:52) (and so on..)

当尝试通过主键获取对象时。

这是 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;
}

我不知道是什么导致了这个问题。其他方法工作得很好...

最佳答案

您正在递归调用 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));
}

希望这有帮助。

关于java - Spring Hibernate,尝试获取实体时堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34331914/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com