Hibernate.initialize(obj)异常

时间:2016-05-21 12:10:47

标签: java hibernate

我有两个相关的类:

class City
{
    @OneToMany( mappedBy = "city" )
    private List<Place> places;
}

class Place
{
    @ManyToOne
    private City city;
}

在控制器中:

@RequestMapping(method = GET)
public String home(Model model)
{
    for ( City city : citiesService.getAllCities() ) //  reading cities from data base
    {
        Hibernate.initialize(city.getPlaces());
    }
    model.addAttribute("cities", citiesService.getAllCity());
    return "home";
}

在视野中我会得到这样的东西:

City1
 - Place1
 - Place2
 - Place3
 - ..
City2
 -Place1
 -Place2
 - ...

但我有一个例外:

org.hibernate.HibernateException: collection is not associated with any session

当我使用FetchType.EAGER而不是LAZY时,它运行正常(当然没有Hibernate.initialize())

我做错了什么?

编辑:

所以,我必须在服务层中有两个方法:

public List<City> getAllTCitiesWithPlaces()
{
        List<City> cities = citiesDao.getAll();
        for ( City city : cities )
            Hibernate.initialize(city.getPlaces());
        return cities;
}

public List<City> getAllTCitiesWithoutPlaces()
{
       return citiesDao.getAll();
}

是吗?

谢谢你兄弟;)

1 个答案:

答案 0 :(得分:2)

发生此问题是因为当您在控制器类中获取位置时,Session已关闭且城市实体与会话分离。

使用您获得城市的方法拨打Hibernate.initialize(city.getPlaces());