我是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
方法有关,但是我不确定这是什么问题。以下是POJOs
或entities
人员
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 + "]";
}
有人可以帮忙吗?
答案 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
,其方法堆栈仍然是溢出。