无法懒惰地初始化集合..没有会话或会话被关闭

时间:2023-01-29 20:34:08

I don't know what else to try, I've updated to Jackson 2, changed to Lazy, used @JsonIgnore... but nothing worked out. Any idea what can it be?

我不知道还有什么可以尝试,我已经更新到Jackson 2,改为Lazy,使用了@JsonIgnore ......但没有任何结果。知道它能是什么吗?

Environment

环境

  • Spring MVC 3.2.5
  • Spring MVC 3.2.5
  • Jackson 2.2
  • 杰克逊2.2
  • Hibernate 3.5.4
  • Hibernate 3.5.4

ERROR Estado HTTP 500 - Could not write JSON: failed to lazily initialize a collection of role: com.javalabs.web.dao.Task.actions, no session or session was closed (through reference chain: java.util.HashMap["actions"]->java.util.ArrayList[0]->com.javalabs.web.dao.TaskAction["task"]->com.javalabs.web.dao.Task["actions"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.javalabs.web.dao.Task.actions, no session or session was closed (through reference chain: java.util.HashMap["actions"]->java.util.ArrayList[0]->com.javalabs.web.dao.TaskAction["task"]->com.javalabs.web.dao.Task["actions"])

错误Estado HTTP 500 - 无法编写JSON:无法懒惰地初始化角色集合:com.javalabs.web.dao.Task.actions,没有关闭会话或会话(通过引用链:java.util.HashMap [“actions “] - >的java.util.ArrayList [0] - > com.javalabs.web.dao.TaskAction [” 任务 “] - > com.javalabs.web.dao.Task [” 行动“]);嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:懒得初始化一个角色集合:com.javalabs.web.dao.Task.actions,没有会话或会话被关闭(通过引用链:java.util.HashMap [ “动作”] - >的java.util.ArrayList [0] - > com.javalabs.web.dao.TaskAction [ “任务”] - > com.javalabs.web.dao.Task [ “行动”])

Error trace

错误跟踪

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: com.javalabs.web.dao.Task.actions, no session or session was closed (through reference chain: java.util.HashMap["actions"]->java.util.ArrayList[0]->com.javalabs.web.dao.TaskAction["task"]->com.javalabs.web.dao.Task["actions"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.javalabs.web.dao.Task.actions, no session or session was closed (through reference chain: java.util.HashMap["actions"]->java.util.ArrayList[0]->com.javalabs.web.dao.TaskAction["task"]->com.javalabs.web.dao.Task["actions"])
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:207)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:189)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:69)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
causa raíz

com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.javalabs.web.dao.Task.actions, no session or session was closed (through reference chain: java.util.HashMap["actions"]->java.util.ArrayList[0]->com.javalabs.web.dao.TaskAction["task"]->com.javalabs.web.dao.Task["actions"])
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:184)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:605)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:394)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:315)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:27)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:204)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:189)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:69)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
causa raíz

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.javalabs.web.dao.Task.actions, no session or session was closed
org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368)
org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:111)
org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:272)
com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:90)
com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:569)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:597)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:186)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:394)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:315)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:27)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:118)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1819)
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:204)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:189)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:69)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)

MODEL

模型

无法懒惰地初始化集合..没有会话或会话被关闭

TaskController.java

TaskController.java

@Controller
public class TaskController {

...

    @RequestMapping(value = "/getactions/{id}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody Map<String, Object> getActions(Principal principal,
            @PathVariable Long id) {
        logger.info("Task controller get actions...");

        List<TaskAction> actions = null;

        if (principal == null) {
            actions = new ArrayList<TaskAction>();
        } else {
            actions = taskActionService.getAllTaskActions(id);
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("actions", actions);
        data.put("number", actions.size());

        return data;
    }
}

Task.java

Task.java

@Entity
@Table(name = "t_task")
public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idTask")
    private long idTask;
    @Size(min = 5, max = 100)
    @Column(name = "taskname")
    private String taskname;
    ...
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "task", orphanRemoval = true)
    private List<TaskAction> actions = new ArrayList<TaskAction>();
    @Column(name = "timestamp")
    private Timestamp timestamp;
...
}

User.java @Entity @Table(name = "t_user") public class User {

User.java @Entity @Table(name =“t_user”)public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "idUser")
private long idUser;

...

@ManyToMany(cascade = { CascadeType.ALL })
@JsonIgnore
@JoinTable(name = "r_userrole", joinColumns = { @JoinColumn(name = "idUser") }, inverseJoinColumns = { @JoinColumn(name = "idRole") })
private Set<Role> roles = new HashSet<Role>();

... }

...}

TaskAction.java

TaskAction.java

@Entity
@Table(name = "t_taskaction")
public class TaskAction {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idTaskAction")
    private long idTaskAction;
    @ManyToOne
    @JoinColumn(name = "idTask", nullable = false)
    private Task task;
    ...
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "idUser", nullable = false)
    private User user;
    @Column(name = "timestamp")
    private Date timestamp;
    ...
}

TaskActionDao.java

TaskActionDao.java

@Repository
@Transactional
@Component("taskActionDao")
public class TaskActionDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    ...

    @SuppressWarnings("unchecked")
    public List<TaskAction> getAllTaskActions() {
        Query q = session().createQuery("from TaskAction");
        List<TaskAction> la = q.list();
        //createQuery("from TaskAction").list();
        System.out.println(">>>>>>>>>>getAllActions>>>>>>>>>>> " + la.size());
        return la;
    }

    @SuppressWarnings("unchecked")
    public List<TaskAction> getAllTaskActions(long idTask) {
        Criteria crit = session().createCriteria(TaskAction.class);
        crit.add(Restrictions.eq("task.idTask", idTask));
        System.out.println(">>>>>>>>getAllActions(id)>>>>>>>>>>>>> " + crit.list().size());
        return crit.list();
    }
}

5 个解决方案

#1


15  

Fist of all, we don't need User.java at all here. It has nothing to it. The issue is related to Task.actions. You load collection of TaskAction, TaskAction has Task and this Task has collection of TaskAction which cannot be initialized. You can add @JsonIgnore to:

首先,我们根本不需要User.java。它什么都没有。该问题与Task.actions有关。你加载TaskAction的集合,TaskAction有Task,这个Task有TaskAction的集合,无法初始化。您可以将@JsonIgnore添加到:

private List<TaskAction> actions = new ArrayList<TaskAction>(); //Task class

or to:

或者:

private Task task; //TaskAction class

You can also try with changing FetchType.LAZY to FetchType.EAGER for collection of actions in Task.java, however I'm not sure it's going to work (circular references)

您也可以尝试将FetchType.LAZY更改为FetchType.EAGER以收集Task.java中的操作,但是我不确定它是否会起作用(循环引用)

#2


5  

Since you are accessing your Object outside the Hibernate Session object, so you should add the annotation @JsonIgnore before each @OneToMany annotation in your model

由于您在Hibernate Session对象之外访问Object,因此您应该在模型中的每个@OneToMany注释之前添加注释@JsonIgnore

#3


1  

Please add annotation @JsonIgnore before each @OneToMany annotation in you entity class My solution

请在实体类My solution中的每个@OneToMany注释之前添加注释@JsonIgnore

@JsonIgnore
@OneToMany(cascade = CascadeType.ALL, mappedBy = "domainDataId")

Thank Shahid Hussain Abbasi

感谢Shahid Hussain Abbasi

#4


0  

I've recently encountered a similar problem: Jackson version 1.9 and lower with birectional relationships (avoiding cycles)

我最近遇到了类似的问题:Jackson版本1.9和更低版本的双向关系(避免循环)

And the solution seems to upgrade to Jackson 2.0, and add to classes the following annotation:

解决方案似乎升级到Jackson 2.0,并添加以下注释类:

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, 
                  property = "idTaskAction")
public class TaskAction

More info

更多信息

#5


0  

I had an issue showing the exception same as above, complaining about the 'no session' but I found that the problem was due to the Entity being referenced in the DTO rather than its ID. So just in case above problem occurs I will suggest to check if one hasn't caused any serialization issue.

我有一个问题显示与上面相同的异常,抱怨'没有会话',但我发现问题是由于在DTO中引用了实体而不是它的ID。所以,如果出现上述问题,我建议检查一个是否没有引起任何序列化问题。

#1


15  

Fist of all, we don't need User.java at all here. It has nothing to it. The issue is related to Task.actions. You load collection of TaskAction, TaskAction has Task and this Task has collection of TaskAction which cannot be initialized. You can add @JsonIgnore to:

首先,我们根本不需要User.java。它什么都没有。该问题与Task.actions有关。你加载TaskAction的集合,TaskAction有Task,这个Task有TaskAction的集合,无法初始化。您可以将@JsonIgnore添加到:

private List<TaskAction> actions = new ArrayList<TaskAction>(); //Task class

or to:

或者:

private Task task; //TaskAction class

You can also try with changing FetchType.LAZY to FetchType.EAGER for collection of actions in Task.java, however I'm not sure it's going to work (circular references)

您也可以尝试将FetchType.LAZY更改为FetchType.EAGER以收集Task.java中的操作,但是我不确定它是否会起作用(循环引用)

#2


5  

Since you are accessing your Object outside the Hibernate Session object, so you should add the annotation @JsonIgnore before each @OneToMany annotation in your model

由于您在Hibernate Session对象之外访问Object,因此您应该在模型中的每个@OneToMany注释之前添加注释@JsonIgnore

#3


1  

Please add annotation @JsonIgnore before each @OneToMany annotation in you entity class My solution

请在实体类My solution中的每个@OneToMany注释之前添加注释@JsonIgnore

@JsonIgnore
@OneToMany(cascade = CascadeType.ALL, mappedBy = "domainDataId")

Thank Shahid Hussain Abbasi

感谢Shahid Hussain Abbasi

#4


0  

I've recently encountered a similar problem: Jackson version 1.9 and lower with birectional relationships (avoiding cycles)

我最近遇到了类似的问题:Jackson版本1.9和更低版本的双向关系(避免循环)

And the solution seems to upgrade to Jackson 2.0, and add to classes the following annotation:

解决方案似乎升级到Jackson 2.0,并添加以下注释类:

@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, 
                  property = "idTaskAction")
public class TaskAction

More info

更多信息

#5


0  

I had an issue showing the exception same as above, complaining about the 'no session' but I found that the problem was due to the Entity being referenced in the DTO rather than its ID. So just in case above problem occurs I will suggest to check if one hasn't caused any serialization issue.

我有一个问题显示与上面相同的异常,抱怨'没有会话',但我发现问题是由于在DTO中引用了实体而不是它的ID。所以,如果出现上述问题,我建议检查一个是否没有引起任何序列化问题。