查询HQL查询的结果时出现PersistentBag.toString()stackoverflow错误

时间:2019-04-07 15:30:19

标签: java hibernate jpa hql

我是Hibernate的初学者,正试图实现HQL查询之一

Query q= em.createQuery("select p from Person p join p.company c");
        List<Person> l = q.getResultList();
        System.out.println(l.get(0));

运行上面的代码时,出现以下错误:

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.StringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.<init>(Unknown Source)
    at hibernate5.testing.onetomany.Person.toString(Person.java:71)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at java.util.AbstractCollection.toString(Unknown Source)
    at org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:527)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at hibernate5.testing.onetomany.Company.toString(Company.java:72)
    at java.lang.String.valueOf(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)

但是,当我注释掉sysout时,它按预期运行。根据堆栈跟踪,它似乎与toString方法有关,但是我不确定这是什么问题。以下是POJOsentities

人员

getters and setters


    @Override
public String toString() {
    return "Person [id=" + id + ", name=" + name + ", company=" + company + "]";
}

公司

 getters and setters


        @Override
        public String toString() {
            return "Company [id=" + id + ", name=" + name + ", persons=" + persons + "]";
        }

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您正面临问题,因为import React, { Component } from 'react' import { Navbar, Nav, NavItem } from 'react-bootstrap'; import { withRouter, Link } from 'react-router-dom'; import './Navbar.css' export default class Navbar extends Component { constructor(props) { super(props); } goBack = () => { this.props.history.goBack(); } render() { return ( <Navbar default collapseOnSelect> <Navbar.Header> <Navbar.Brand> My App </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav pullRight> <NavItem eventKey={1} href="https://app.com"> Home </NavItem> <NavItem onClick={this.goBack}>Go Back</NavItem> </Nav> </Navbar.Collapse> </Navbar> ) } } 呼叫Person#toString,而Company#toString再次呼叫Company#toString

所以,发生的事情是当Person#toString调用它时,它称为以下toString定义:

Person#toSting

现在可以看到您也污染了公司,这意味着您的退货声明实际上变成了 @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", company=" + company + "]"; } 。因此,它调用Company#toString(),现在看起来"Person [id=" + id + ", name=" + name + ", company=" + company.toString() + "]";的实现,其中包含Company#toString()对象,字符串化。再次调用persons,其方法堆栈仍然是溢出。