4

I am working on a Spring-MVC application in which I am using hibernate as the ORM tool as PostgreSQL as the database. Currently I am having a problem when I am accessing data from the database for a few methods. All the times, the error is same. I am not persisting anything, but rather just requesting data.

The problem is always happening at getUniqueResult for a 3-4 of the DAO methods. Any help would be nice. Also, I checked the answers, but they give only some scenarios, none of them applicable as I am just querying for data.

Error code :

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: Found shared references to a collection: com.journaldev.spring.model.Person.canvas1

org.hibernate.HibernateException: Found shared references to a collection: com.journaldev.spring.model.Person.canvas1
        com.journaldev.spring.dao.GroupAttachmentsDAOImpl.returnAttachmentCount(GroupAttachmentsDAOImpl.java:108)

Code in question :

   @Override
    public int returnAttachmentCount(int mnoticesid) {
        session = this.sessionFactory.getCurrentSession();
        Query query = session.createQuery("select count(*) from GroupAttachments as a where a.mnotedata.mnoticesid=:mnoticesid");
        query.setParameter("mnoticesid",mnoticesid);
return Integer.valueOf(String.valueOf(query.uniqueResult()));

    }

Any help would be nice. Thanks a lot. :-)

Edit

Person mapping :

   @OneToMany(mappedBy = "person1",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    @Index(name = "canvas1index")
    private Set<Canvas> canvas1 = new HashSet<Canvas>();

    public Set<Canvas> getCanvas1() {
        return canvas1;
    }

    public void setCanvas1(Set<Canvas> canvas1) {

        this.canvas1 = canvas1;
    }

    @OneToMany(mappedBy = "userConversation",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    private Set<Conversation> conversations = new HashSet<Conversation>();

    public Set<Conversation> getConversations(){
        return this.conversations;
    }

    public void setConversations(Set<Conversation> conversations){
        this.conversations=conversations;
    }

    @OneToMany(mappedBy = "user1Conversation",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    private Set<Conversation> conversation1 = new HashSet<>();

    public Set<Conversation> getConversation1(){
        return this.conversation1;
    }

    public void setConversation1(Set<Conversation> conversation1){
        this.conversation1=conversation1;
    }


    @OneToMany(mappedBy = "replyingPerson",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    @Index(name = "replyingpersonindex")
    private Set<Replies> repliesSet = new HashSet<>();

    public Set<Replies> getRepliesSet(){
        return this.repliesSet;
    }

    public void setRepliesSet(Set<Replies> repliesSet){
        this.repliesSet = repliesSet;
    }


    @OneToMany(mappedBy = "personStatistics",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    private Set<Statistics> statisticsSet = new HashSet<>();

    public Set<Statistics> getStatisticsSet(){
        return this.statisticsSet;
    }

    public void setStatisticsSet(Set<Statistics> statisticsSet){
        this.statisticsSet = statisticsSet;
    }

Above are all Person mappings

Canvas mappings :

 @ManyToOne
    @JoinColumn(name = "id",nullable = false)
    @JsonIgnore
    @Index(name = "person1")
    private Person person1;

    public Person getPerson1() {
        return person1;
    }

    public void setPerson1(Person person1) {
        this.person1 = person1;
    }

    public int getPerson1id(){
        return this.person1.getId();
    }

    @OneToMany(mappedBy = "canvas2",fetch=FetchType.LAZY, cascade = CascadeType.REMOVE)
    @JsonIgnore
    @Index(name = "section2")
    private Set<Section> section2 = new HashSet<Section>();

    public Set<Section> getSection2() {
        return section2;
    }

    public void setSection2(Set<Section> section2) {
        this.section2 = section2;
    }

These are all the mappings, and completely unrealted to GroupAttachments as I described.

Edit

Complete stack trace :

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: Found shared references to a collection: com.journaldev.spring.model.Person.canvas1


type Exception report
message Request processing failed; nested exception is org.hibernate.HibernateException: Found shared references to a collection: com.journaldev.spring.model.Person.canvas1
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Found shared references to a collection: com.journaldev.spring.model.Person.canvas1
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
        org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.apache.catalina.filters.ExpiresFilter.doFilter(ExpiresFilter.java:1179)
        org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        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.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
        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.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
        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:344)
        org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
org.hibernate.HibernateException: Found shared references to a collection: com.journaldev.spring.model.Person.canvas1
        org.hibernate.engine.internal.Collections.processReachableCollection(Collections.java:180)
        org.hibernate.event.internal.FlushVisitor.processCollection(FlushVisitor.java:59)
        org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:121)
        org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:82)
        org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:76)
        org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:172)
        org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
        org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
        org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:61)
        org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1191)
        org.hibernate.internal.SessionImpl.list(SessionImpl.java:1257)
        org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
        org.hibernate.internal.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:966)
        com.journaldev.spring.dao.GroupAttachmentsDAOImpl.returnAttachmentCount(GroupAttachmentsDAOImpl.java:108)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        java.lang.reflect.Method.invoke(Unknown Source)
        org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
        org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
        org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        com.sun.proxy.$Proxy104.returnAttachmentCount(Unknown Source)
        com.journaldev.spring.service.GroupAttachmentsServiceImpl.returnAttachmentCount(GroupAttachmentsServiceImpl.java:228)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        java.lang.reflect.Method.invoke(Unknown Source)
        org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
        org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
        org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        com.sun.proxy.$Proxy94.returnAttachmentCount(Unknown Source)
        com.journaldev.spring.dao.GroupNotesDAOImpl.listGroupNotesBySectionId(GroupNotesDAOImpl.java:137)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        java.lang.reflect.Method.invoke(Unknown Source)
        org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
        org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
        org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        com.sun.proxy.$Proxy109.listGroupNotesBySectionId(Unknown Source)
        com.journaldev.spring.service.GroupNotesServiceImpl.listGroupNotesBySectionId(GroupNotesServiceImpl.java:495)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        java.lang.reflect.Method.invoke(Unknown Source)
        org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
        org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
        org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
        org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
        org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
        com.sun.proxy.$Proxy90.listGroupNotesBySectionId(Unknown Source)
        com.journaldev.spring.controller.PersonController.listNotes(PersonController.java:1442)
        com.journaldev.spring.controller.PersonController$$FastClassBySpringCGLIB$$f2c66d65.invoke(<generated>)
        org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:640)
        com.journaldev.spring.controller.PersonController$$EnhancerBySpringCGLIB$$4fd054fd_2.listNotes(<generated>)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        java.lang.reflect.Method.invoke(Unknown Source)
        org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
        org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
        org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
        org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
        org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
        org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
        org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
        org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
        org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.apache.catalina.filters.ExpiresFilter.doFilter(ExpiresFilter.java:1179)
        org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
        org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        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.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
        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.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:125)
        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:344)
        org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)

ListNotesMethod :

@Override
    public List<Notes> listNotesBySectionId(int sectionid) {
        session = this.sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Notes as n where n.section1.sectionid=:sectionid and n.noteDisabled=false and n.noteInActive=false order by n.noteorder");
        query.setParameter("sectionid", sectionid);

        List<Notes> notesList = query.list();
        if(notesList.isEmpty()){
            return notesList;
        } else {
            double i = 1.0;
            for (Notes notes : notesList) {
                notes.setNoteorder(i);
                notes.setNotetext(notes.getNotetext().replaceAll("\\r?\\n", "<br/>"));
                notes.setNotetag(notes.getNotetag().replaceAll("\\r?\\n", "<br/>"));
                i = i + 1;
               notes.setAttachCount(this.attachmentService.returnAttachmentCount(notes.getNoticesid()));
            }
            return notesList;
        }
    }




Also returnAttachmentCount()

    @Override
    public int returnAttachmentCount(int noticesid) {
        session = this.sessionFactory.getCurrentSession();
        Query query = session.createQuery("select count(*) from Attachment as a where a.notedata.noticesid=:noticesid");
        query.setParameter("noticesid",noticesid);
        return new Integer(String.valueOf(query.uniqueResult()));
    }
We are Borg
  • 5,117
  • 17
  • 102
  • 225

2 Answers2

4

This is a recurring question, you can see a similar one with the suggested solutions here. Basically, you are assigning the same collection instance to more than one entity instance.

Why does this happen in the query? Well, you did not post the entire stack trace. There we would probably see that the exception is actually thrown on dirty check during automatic flush before query execution - it has nothing to do with this specific query (or the getUniqueResult method).

Recheck how you assign values in one-to-many mappings for Person.canvas1 (and for other entities which could get the same reference to the 'already used' collection instance). The rule of thumb is (pseudo-code):

entity.collection = new ArrayList(otherCollectionInstance);

or

entity.collection = new ArrayList();
entity.collection.addAll(otherCollectionInstance)

or (in case of an update of an already persisted (managed) entity instance)

entity.collection.clear();
entity.collection.addAll(otherCollectionInstance)

That's why it's a good convention to use field initialization to initialize to-many associations to an empty collection:

@Entity
public class MyEntity {
   @OneToMany(...)
   private Collection<MyAssociatedEntity> = new ArrayList<>();
}

EDIT

There seems to be some other reasons for this to happen, some of them described here.

In that regard I see strange mapping for your Canvas entity:

@ManyToOne
@JoinColumn(name = "id",nullable = false)
@JsonIgnore
@Index(name = "person1")
private Person person1;

Should join column be something else like "PERSON_ID"?

Community
  • 1
  • 1
Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
  • I am not calling/querying/anything with Collections, and as far as the One-to-many mapping goes, that is exactly the same way as you pasted I am doing it, but I will still post my mappings in main post. Gimme 5. – We are Borg May 21 '15 at 12:17
  • Ok, could you now check all the places where you call `setCanvas1` method on `Person` objects? You should not call it, you should use `person.getCanvas1().addAll(canvasCollection)`. – Dragan Bozanovic May 21 '15 at 12:32
  • None, I am not adding canvases in bulk, I am only using like this : person1.getCanvas1().add(canvas);. The worst part is, I am not even adding a canvas, or even doing anything with canvas and I am getting that error. – We are Borg May 21 '15 at 12:36
  • Ok, then could you please post entire stack trace of the exception? Also, can you delete `setCanvas1` method from the `Person` class and try to reproduce the issue? Maybe some framework invokes it reflectively (Hibernate should not complain since you are using field access). – Dragan Bozanovic May 21 '15 at 12:42
  • Here is the complete stacktrace : http://pastebin.com/vV60cDmn . My colleague is testing after remove the setMethod, this problem started when we started using AJAX for making making multiple requests to GroupNotes, again not related to person or Canvas. But we will try and will keep you updated. – We are Borg May 21 '15 at 12:46
  • This is becoming strange. Could you then show us the code in listNotes and listGroupNotesBySectionId methods (I see them in stack trace)? You are reading Person objects there I assume, because Hibernate dirty-checks them on flush. – Dragan Bozanovic May 21 '15 at 12:58
  • Also, could you please edit the question to include the stack trace and relevant code parts instead of using external links, so that everything is in one place and easy to inspect when somebody encounters a similar issue later? – Dragan Bozanovic May 21 '15 at 13:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78423/discussion-between-dragan-bozanovic-and-we-are-borg). – Dragan Bozanovic May 21 '15 at 13:14
  • Please see the edited part of the answer, it may also be the cause of the issue. – Dragan Bozanovic May 21 '15 at 15:06
  • Nope, just id just works fine, Hibernate is able to map that to Person class and then it looks for id. – We are Borg May 21 '15 at 15:07
  • Ok, how can you have two Canvases for one Person? This id relates to id column in Canvas table. Let's get back to chat. :) – Dragan Bozanovic May 21 '15 at 15:09
  • Sorry, I was away, please come back on chat. Thanks. – We are Borg May 21 '15 at 15:16
0

This error usually happens where an entity (set of class a) of one type is assigned to a set of another entity (set of class B). In your example - is there a collection of canvas on groupAttachments?

Here are couple of examples i found - https://forum.hibernate.org/viewtopic.php?f=1&t=949652

Caused by: org.hibernate.HibernateException: Found shared references to a collection

Community
  • 1
  • 1
Paul John
  • 1,626
  • 1
  • 13
  • 15
  • No, the mapping is this way, person --> Canvas, GroupMembers -->GroupCanvas --->GroupSection -->GroupNotes --> GroupAttachments. The arrow indicates one to many mapping, eg : One person can have many canvases. But person and canvas are unrealted to GroupAttachments. – We are Borg May 21 '15 at 11:35
  • Looking at the error u posted and the relationship above - is there a way - somehow that a groupAttachment is getting assigned a canvas (a canvas that is already - Person.canvas1) – Paul John May 21 '15 at 11:46
  • There is no mapping or even a remote connection for Person or canvas with GroupAttachment. Any ideas? – We are Borg May 21 '15 at 11:47