问题描述
今天在学习Hibernate一对一关联的时候,跟平常一样,写POJO,然后测试时,报了Exceptioninthread"main"java.lang.StackOverflowError异常,百度得知是程序陷入了无限循环,但就是一个简单的JavaBean,也没有哪段程序会导致错误,然后经过测试,给Person和IdCard加入了无参构造,程序就能正常运行了,但不知道原理是什么,求大神解答packagecom.wss.dao;publicclassPerson{privateIntegerid;privateStringname;privateIdCardidCard;publicIntegergetId(){returnid;}publicvoidsetId(Integerid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicIdCardgetIdCard(){returnidCard;}publicvoidsetIdCard(IdCardidCard){this.idCard=idCard;}publicPerson(){//TODOAuto-generatedconstructorstub}}
packagecom.wss.daoUtil;importorg.hibernate.Session;importorg.hibernate.SessionFactory;importorg.hibernate.Transaction;importorg.hibernate.cfg.Configuration;importcom.wss.dao.IdCard;importcom.wss.dao.Person;publicclassTest{publicstaticvoidmain(String[]args){Configurationcfg=newConfiguration().configure();SessionFactorysf=cfg.buildSessionFactory();Sessionsession=sf.openSession();Transactiontr=session.beginTransaction();System.out.println("a");//新建对象Personperson=newPerson();person.setName("张三");IdCardidCard=newIdCard();idCard.setNumber("341218575464");//建立联系tr.begin();person.setIdCard(idCard);idCard.setOwner(person);//保存session.save(person);session.save(idCard);//提交事件tr.commit();session.close();}}
解决方案
解决方案二:
你把SQL语句打印出来就知道了,然后你这个应该是双向一对一吧,你配置正确了嘛?把idCard.setOwner(person);删了试一试
解决方案三:
删掉idCard.setOwner(person);和session.save(idCard);试试
解决方案四:
好像有时候对象相互引用死循环会出这个异常