QueryManager implements IQueryManager { @Override public Collection<IMessageUnitEntity> getMessageUnitsWithLastStateChangedBefore(Date maxLastChangeDate) throws PersistenceException { List<MessageUnit> jpaResult = null; final EntityManager em = EntityManagerUtil.getEntityManager(); final String queryString = "SELECT mu " + "FROM MessageUnit mu JOIN FETCH mu.states s1 " + "WHERE s1.PROC_STATE_NUM = (SELECT MAX(s2.PROC_STATE_NUM) FROM mu.states s2) " + "AND s1.START <= :beforeDate"; try { em.getTransaction().begin(); jpaResult = em.createQuery(queryString, MessageUnit.class) .setParameter("beforeDate", maxLastChangeDate, TemporalType.TIMESTAMP) .getResultList(); } catch (final Exception e) { throw new PersistenceException("Could not execute query \"getMessageUnitsWithLastStateChangedBefore\"", e); } finally { em.getTransaction().commit(); em.close(); } return JPAEntityHelper.wrapInEntity(jpaResult); }  @Override List<V> getMessageUnitsInState(
               Class<T> type, Direction direction, ProcessingState[] states); @Override Collection<IMessageUnitEntity> getMessageUnitsWithId(String messageId, 
    															Direction... direction); @Override Collection<IMessageUnitEntity> getMessageUnitsWithLastStateChangedBefore(Date maxLastChangeDate); @Override List<V> getMessageUnitsForPModesInState(Class<T> type,
                                    Collection<String> pmodeIds, ProcessingState state); @Override void ensureCompletelyLoaded(V messageUnit); static void loadCompletely(MessageUnit jpaMessageUnit); @Override int getNumberOfTransmissions(IUserMessageEntity userMessage); @Override boolean isAlreadyProcessed(final IUserMessage userMessage); List<IMessageUnitEntity> getMessageUnitHistory(final Date start, final int max);  }
@Test public void getMessageUnitsWithLastStateChangedBefore() throws PersistenceException { Collection<IMessageUnitEntity> result = queryManager.getMessageUnitsWithLastStateChangedBefore(daysBack(15)); assertTrue(Utils.isNullOrEmpty(result)); result = queryManager.getMessageUnitsWithLastStateChangedBefore(daysBack(10)); assertFalse(Utils.isNullOrEmpty(result)); assertEquals(1 , result.size()); IMessageUnit mu = result.iterator().next(); assertEquals(TestData.userMsg1.getMessageId(), mu.getMessageId()); result = queryManager.getMessageUnitsWithLastStateChangedBefore(mu.getCurrentProcessingState().getStartTime()); assertFalse(Utils.isNullOrEmpty(result)); assertEquals(1 , result.size()); assertEquals(TestData.userMsg1.getMessageId(), result.iterator().next().getMessageId()); Calendar currentStateTime = Calendar.getInstance(); currentStateTime.setTime(mu.getCurrentProcessingState().getStartTime()); currentStateTime.add(Calendar.MINUTE, -1); result = queryManager.getMessageUnitsWithLastStateChangedBefore(currentStateTime.getTime()); assertTrue(Utils.isNullOrEmpty(result)); result = queryManager.getMessageUnitsWithLastStateChangedBefore(daysBack(6)); assertFalse(Utils.isNullOrEmpty(result)); assertEquals(5 , result.size()); }