title: Hibernate. violates foreign key constraint in cache
body: <p>I have following service:</p>
  
  <pre><code>@Service
  @Transactional
  public class blablaService{
        ....  
        @Override
        public void deleteSystemGroups(Set&lt;Long&gt; ids) {
            List&lt;Terminal&gt; terminals = terminalDao.findAll();
            Set&lt;SystemGroup&gt; systemGroupsToDelete = systemGroupDao.getByIds(ids);
            for (Terminal terminal: terminals) {
                terminal.getTerminalSystemGroupsSet().removeAll(systemGroupsToDelete);   // important
              terminalDao.updateTerminal(terminal);
            }
            systemGroupDao.delete(ids);  // important
        }
  }
  </code></pre>
  
  <p>and following dao:</p>
  
  <pre><code>public boolean updateTerminal(Terminal terminal) {
    Session session = sessionFactory.getCurrentSession();
    session.update(terminal);
    session.flush();  // ATTENTION HERE!!!
    return true;
   }
  </code></pre>
  
  <p>Now it is working but if remove line</p>
  
  <pre><code>session.flush();
  </code></pre>
  
  <p>I see following error:</p>
  
  <pre><code>org.postgresql.util.PSQLException: ERROR: update or delete on table "system_group" violates foreign key constraint "fk2593ed524a9b4be6" on table "terminal_system_group"|  Detail: Key (group_id)=(2) is still referenced from table "terminal_system_group".
  </code></pre>
  
  <p>I understand the cause of the problem but I am not sure that my fix is good.</p>
  
  <p>Can you advise better solution?</p>