关闭实体经理的正确方法

时间:2014-02-20 07:58:23

标签: hibernate jboss

我有以下REST服务

public class myRestService {
    @SuppressWarnings("unchecked")
    @GET
    @Path("")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getApplications(
            @QueryParam("Id") String Id) throws Exception {
        EntityManager manager = HibernateUtil.getEntityManager();
        EntityTransaction transaction = manager.getTransaction();
        List<Application> applications = new ArrayList<Application>(0);

        try {
            transaction.begin();
            Query query = manager.createQuery("select a from Application a where id= :Id");
            query.setParameter("Id", Id);
            applications = query.getResultList();
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //manager.close();
        }

        return Response.ok(applications).build();
    }
}

返回语句具有不定式循环,如下所示。我认为这是因为我没有关闭经理。

 [{"name":"app1","id":1,"host":"http://www.app1.com","appType":"1","advertiser":{"name":"advertiser1","id":3,"status":"Inactive","applications":[{"name":"app1","id":1,"host":"http://www.app1.com","appType":"1","advertiser":
    {"name":"advertiser1","id":3,"status":"Inactive","applications":......................

如果我关闭了经理,我会收到org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.model.Advertiser.applications, could not initialize proxy -错误。我认为这是因为没有连接会话。

1 个答案:

答案 0 :(得分:0)

我认为你面对这种无限循环的原因是你的数据库配置有一个循环。

像这样(例子):

    A db record references B db record
    B db record references A db record
...