Hibernate查询

一、Hibernate的双向关联关系,你在哪一端设置lazy属性,那么在查询时就对哪一端起作用。例如双向多对一关联关系中,在一端中设置lazy属性为true,那么在查询一端的记录时就不会把关联的多端的记录查询出来,等到需要的时候再查询出来。

二、Hibernate的双向多对一关联关系中如果对两端的对象都调用toString()方法的话会出现堆栈溢出的现象,通常的解决办法是不要两端都重写toString()方法,不写或者只写一端的就可以。比如Country类为一端,Competition为多端。那么如下代码是不会报错的。

        Country country = (Country) session.get(Country.class, 1);
        Set<Competition> competitions = country.getCompetitions();

但是你要打印某一段的对象就都会出现无限递归,堆栈溢出的情况。如下:

打印多端的集合会报错

        Country country = (Country) session.get(Country.class, 1);
        Set<Competition> competitions = country.getCompetitions();
        System.out.println(competitions);//打印多端的集合对报错。

打印多端的某一个对象也会报错

        for (Competition c : competitions)
        {
            System.out.println(c);
        }

打印一端的某一个对象也会报错。。。。。。这里不列举了。要就把toString方法里另一端关联的对象去掉。

原文地址:https://www.cnblogs.com/GooPolaris/p/7919877.html