title: Running find throws a Detached entity passed to persist exception
body: <p>I'm struggling with an error I get with Spring and Hibernate when trying to update a resource through a REST API.  </p>
  
  <p>I have simplified the case with minimal extra attributes.  </p>
  
  <h3>Basic Model overview</h3>
  
  <p>I'm trying to update a resource called <code>Rule</code>.<br>
  <code>Rule</code> has a <code>ThingGroup</code> which is a representation of a group of objects.
  <code>Rule</code>has also a set of <code>Event</code> which represents the activation ranges of the rule.
  During the execution of the application, the run will have to check some parameter on this thing group to trigger alerts or not.</p>
  
  <h3>Error thrown by Hibernate</h3>
  
  <p>My issue is that when using the <code>update</code> method in the rule service below, it fails with this error.  </p>
  
  <pre><code> org.hibernate.PersistentObjectException: detached entity passed to persist: com.smartobjectsecurity.common.domain.rule.Event
  at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:276)
  at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
  at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
  at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
  at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
  at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:105)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
  at com.sun.proxy.$Proxy117.findOne(Unknown Source)
  at com.smartobjectsecurity.common.service.thing.ThingGroupServiceImpl.find(ThingGroupServiceImpl.java:62)
  at com.smartobjectsecurity.common.service.thing.ThingGroupServiceImpl.find(ThingGroupServiceImpl.java:1)
  at com.smartobjectsecurity.common.service.GenericServiceImpl.find(GenericServiceImpl.java:1)
  at com.smartobjectsecurity.common.service.GenericServiceImpl$$FastClassBySpringCGLIB$$daaa7267.invoke(&lt;generated&gt;)
  at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
  at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
  at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
  at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
  at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
  at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
  at com.smartobjectsecurity.common.service.thing.ThingGroupServiceImpl$$EnhancerBySpringCGLIB$$aa452fd7.find(&lt;generated&gt;)
  at com.smartobjectsecurity.common.service.rule.RuleServiceImpl.update(RuleServiceImpl.java:219)
  </code></pre>
  
  <h3>RuleService's update method</h3>
  
  <p>Below is the ruleService <code>update</code> method.<br>
  First I need to update the associated reaction group using the reactionGroup service.  </p>
  
  <pre><code>@Transactional
  public Rule update(final Rule rule, User user) throws UnknownEntityException, MyBadRequestException {
       final Long id = rule.getId();
       Rule found = null;
       try {
            found = find(id, user);
            found.setEvents(rule.getEvents());
            thingGroupService.find(rule.getThingGroup().getId(), user);
            found.setThingGroup(rule.getThingGroup());
            found = dao.saveAndFlush(found);
  
       } catch (final UnknownEntityException e) {
            final UnknownEntityException ex = new UnknownEntityException("UnknownEntity/ResourceException.rule", "update_unknown_rule");
            ex.setParameters(new Object[] { id });
            throw ex;
       }
  
       return found;
  }
  </code></pre>
  
  <h3>ThingGroupService's find method</h3>
  
  <pre><code> @Override
   @Transactional(rollbackFor = UnknownEntityException.class )
   public ThingGroup find(final Long id, User user) throws UnknownEntityException {
        logger.debug("-&gt; find, id = " + id);
        final ThingGroup found = getDao().findOne(buildSpecificationForIdAndUser(id, user));
        if (found == null) {
             final UnknownEntityException ex = new UnknownEntityException("UnknownEntity/ResourceException.thingGroup", "unknown_thingGroup");
             ex.setParameters(new Object[] { id });
             throw ex;
        }
        logger.debug("&lt;- find : " + found);
        return found;
   }
  </code></pre>
  
  <p>As requested here are the <code>buildSpecificationForIdAndUser</code> and <code>buildSpecificationForUser</code> methods.<br>
  They are used to build search restrictions based on the permissions of the users.  </p>
  
  <pre><code> @Transactional
  protected Specification&lt;ENTITY&gt; buildSpecificationForIdAndUser(final ID id,final User user){
      return new Specification&lt;ENTITY&gt;() {
          @Override
          public Predicate toPredicate(Root&lt;ENTITY&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder builder) {
              Expression&lt;Long&gt; entityId = root.get("id");
  
  
              Predicate userPredicate = buildSpecificationForUser(user).toPredicate(root, query, builder);
  
              return builder.and(
                  builder.equal(entityId, id),
                  userPredicate
              );
          }
      };
  }
  
   @Override
  @Transactional
  protected Specification&lt;ThingGroup&gt; buildSpecificationForUser(final User user) {
      return new Specification&lt;ThingGroup&gt;() {
          @Override
          public Predicate toPredicate(Root&lt;ThingGroup&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder builder) {
              Expression&lt;Collection&lt;User&gt;&gt; managersOfThingGroup = root.get("managers");
              Expression&lt;Company&gt; thingGroupCompany = root.get("company");
  
              Predicate isManager = builder.isMember(user, managersOfThingGroup);
              Predicate isSameCompany = builder.equal(thingGroupCompany,user.getCompany());
  
              return builder.and(isSameCompany,isManager);
  
          }
      };
  }
  </code></pre>
  
  <h3>Where the error lies</h3>
  
  <p>When attempting to run <code>thingGroupService.find(rule.getThingGroup().getId(), user);</code> , Hibernate suddenly throws the exception about the Event entoty (detached entity passed to persist).<br>
  I really don't know what is wrong here.<br>
  I have been searching of various forums for several days without finding the cause of my issue.  </p>
  
  <h3>Question</h3>
  
  <p>Why does the <code>Event</code> entity suddenly become detached from the session after running a find on a <code>ThingGroup</code> resource which has nothing to do whith event ?</p>