Java Code Examples for org.springframework.orm.hibernate3.HibernateTemplate

The following examples show how to use org.springframework.orm.hibernate3.HibernateTemplate. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void findModificationsFor_shouldCacheModifications() {
    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);

    ArrayList modifications = new ArrayList();
    when(mockTemplate.find("FROM Modification WHERE materialId = ? AND id BETWEEN ? AND ? ORDER BY id DESC", new Object[]{10L, -1L, -1L})).thenReturn(modifications);
    MaterialInstance materialInstance = material().createMaterialInstance();
    materialInstance.setId(10);
    when(mockTemplate.findByCriteria(any(DetachedCriteria.class))).thenReturn((List) asList(materialInstance));

    PipelineMaterialRevision pmr = pipelineMaterialRevision();
    List<Modification> actual;
    actual = repo.findModificationsFor(pmr);
    actual = repo.findModificationsFor(pmr);

    assertSame(modifications, actual);

    verify(mockTemplate, times(1)).find("FROM Modification WHERE materialId = ? AND id BETWEEN ? AND ? ORDER BY id DESC", new Object[]{10L, -1L, -1L});
}
 
Example 2
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void findModificationsSince_shouldCacheResults() {
    SvnMaterial material = MaterialsMother.svnMaterial();
    MaterialRevision zero = saveOneScmModification(material, "user1", "file1");
    MaterialRevision first = saveOneScmModification(material, "user1", "file1");
    MaterialRevision second = saveOneScmModification(material, "user2", "file2");
    MaterialRevision third = saveOneScmModification(material, "user2", "file2");

    repo.findModificationsSince(material, first);

    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);
    List<Modification> modifications = repo.findModificationsSince(material, first);
    assertThat(modifications.size(), is(2));
    assertEquals(third.getLatestModification(), modifications.get(0));
    assertEquals(second.getLatestModification(), modifications.get(1));
    verifyNoMoreInteractions(mockTemplate);
}
 
Example 3
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void findLatestModifications_shouldCacheResults() {
    SvnMaterial material = MaterialsMother.svnMaterial();
    MaterialInstance materialInstance = material.createMaterialInstance();
    repo.saveOrUpdate(materialInstance);

    Modification mod = ModificationsMother.oneModifiedFile("file3");
    mod.setId(8);

    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);
    when(mockTemplate.execute(any())).thenReturn(mod);

    repo.findLatestModification(materialInstance);

    Modification modification = repo.findLatestModification(materialInstance);
    assertSame(mod, modification);

    verify(mockTemplate, times(1)).execute(any());

}
 
Example 4
public void reindexDependents(final HibernateTemplate hibernateTemplate, final BaseDO< ? > obj)
{
  new Thread() {
    @Override
    public void run()
    {
      final SessionFactory sessionFactory = hibernateTemplate.getSessionFactory();
      final HibernateTemplate template = new HibernateTemplate(sessionFactory);
      final Session session = template.getSessionFactory().openSession();
      final Set<String> alreadyReindexed = new HashSet<String>();
      final List<Entry> entryList = map.get(obj.getClass());
      reindexDependents(template, session, obj, entryList, alreadyReindexed);
      session.disconnect();
      final int size = alreadyReindexed.size();
      if (size >= 10) {
        log.info("Re-indexing of " + size + " objects done after updating " + obj.getClass().getName() + ":" + obj.getId());
      }
    }
  }.start();
}
 
Example 5
private void reindexDependents(final HibernateTemplate hibernateTemplate, final Session session, final BaseDO< ? > obj,
    final List<Entry> entryList, final Set<String> alreadyReindexed)
{
  if (CollectionUtils.isEmpty(entryList) == true) {
    // Nothing to do.
    return;
  }
  for (final Entry entry : entryList) {
    final RegistryEntry registryEntry = Registry.instance().getEntryByDO(entry.clazz);
    if (registryEntry == null) {
      // Nothing to do
      return;
    }
    final List< ? > result = getDependents(hibernateTemplate, registryEntry, entry, obj);
    if (result != null) {
      for ( Object dependentObject : result) {
        if (dependentObject instanceof Object[]) {
          dependentObject = ((Object[])dependentObject)[0];
        }
        if (dependentObject instanceof BaseDO) {
          reindexDependents(hibernateTemplate, session, (BaseDO< ? >) dependentObject, alreadyReindexed);
        }
      }
    }
  }
}
 
Example 6
Source Project: JgFramework   Source File: BaseDao.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<IBaseModel> findAll(int start, int limit) {
    log.debug("finding all Object instances");
    try {
        HibernateTemplate ht = getHibernateTemplate();
        int PRE_MAX_RESULT = ht.getMaxResults();
        int PRE_LIMIT = ht.getFetchSize();
        ht.setMaxResults(limit);
        ht.setFetchSize(start);
        String queryString = "from " + this.modelName;
        List<IBaseModel> list = ht.find(queryString);
        ht.setMaxResults(PRE_MAX_RESULT);
        ht.setFetchSize(PRE_LIMIT);
        return list;
    } catch (RuntimeException re) {
        log.error("find all failed", re);
        throw re;
    }
}
 
Example 7
@Test
public void testHibernateDaoSupportWithHibernateTemplate() throws Exception {
	HibernateTemplate template = new HibernateTemplate();
	final List test = new ArrayList();
	HibernateDaoSupport dao = new HibernateDaoSupport() {
		@Override
		protected void initDao() {
			test.add("test");
		}
	};
	dao.setHibernateTemplate(template);
	dao.afterPropertiesSet();
	assertEquals("Correct HibernateTemplate", template, dao.getHibernateTemplate());
	assertEquals("initDao called", test.size(), 1);
}
 
Example 8
Source Project: gocd   Source File: PipelineRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    session = mock(Session.class);
    sqlQuery = mock(SQLQuery.class);
    sessionFactory = mock(SessionFactory.class);
    hibernateTemplate = mock(HibernateTemplate.class);
    goCache = mock(GoCache.class);
    databaseStrategy = mock(Database.class);
    when(databaseStrategy.getQueryExtensions()).thenReturn(mock(QueryExtensions.class));
    pipelineRepository = new PipelineRepository(sessionFactory, goCache, databaseStrategy);
    pipelineRepository.setHibernateTemplate(hibernateTemplate);
    transactionTemplate = mock(TransactionTemplate.class);
    transactionSynchronizationManager = mock(TransactionSynchronizationManager.class);
}
 
Example 9
Source Project: gocd   Source File: PipelineRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
private void stubPipelineInstancesInDb(Object[]... rows) {
    pipelineRepository.setHibernateTemplate(new HibernateTemplate() {
        @Override
        public <T> T execute(HibernateCallback<T> action) throws DataAccessException {
            try {
                return action.doInHibernate(session);
            } catch (SQLException e) {
                throw new RuntimeException();
            }
        }
    });
    when(session.createSQLQuery(nullable(String.class))).thenReturn(sqlQuery);
    when(sqlQuery.list()).thenReturn(Arrays.asList(rows));
}
 
Example 10
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findPipelineMaterialRevisions_shouldCacheResults() {
    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);

    repo.findPipelineMaterialRevisions(2);
    repo.findPipelineMaterialRevisions(2);

    verify(mockTemplate, times(1)).find("FROM PipelineMaterialRevision WHERE pipelineId = ? ORDER BY id", 2L);
}
 
Example 11
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findLatestModifications_shouldQueryIfNotEnoughElementsInCache() {
    SvnMaterial material = MaterialsMother.svnMaterial();
    MaterialRevision mod = saveOneScmModification(material, "user2", "file3");
    goCache.remove(repo.latestMaterialModificationsKey(repo.findMaterialInstance(material)));
    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);
    when(mockTemplate.execute(any(HibernateCallback.class))).thenReturn(mod.getModification(0));
    Modification modification = repo.findLatestModification(repo.findMaterialInstance(material));

    assertThat(modification, is(mod.getLatestModification()));
    verify(mockTemplate).execute(any(HibernateCallback.class));
}
 
Example 12
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findOrCreateFrom_shouldCacheMaterialInstanceOnCreate() throws Exception {
    Material svn = MaterialsMother.svnMaterial("url", null, "username", "password", false, null);

    MaterialInstance instance = repo.findOrCreateFrom(svn);
    assertThat(instance, is(notNullValue()));

    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);

    MaterialInstance cachedInstance = repo.findMaterialInstance(svn);
    assertSame(instance, cachedInstance);

    verifyNoMoreInteractions(mockTemplate);
}
 
Example 13
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findMaterialInstance_shouldCacheMaterialInstance() throws Exception {
    Material svn1 = MaterialsMother.svnMaterial("url", null, "username", "password", false, null);
    repo.saveOrUpdate(svn1.createMaterialInstance());

    MaterialInstance instance = repo.findMaterialInstance(svn1);

    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);

    MaterialInstance cachedInstance = repo.findMaterialInstance(svn1);
    assertSame(instance, cachedInstance);

    verifyNoMoreInteractions(mockTemplate);
}
 
Example 14
private void reindexDependents(final HibernateTemplate hibernateTemplate, final Session session, final BaseDO< ? > obj,
    final Set<String> alreadyReindexed)
{
  if (alreadyReindexed.contains(getReindexId(obj)) == true) {
    if (log.isDebugEnabled() == true) {
      log.debug("Object already re-indexed (skipping): " + getReindexId(obj));
    }
    return;
  }
  session.flush(); // Needed to flush the object changes!
  final FullTextSession fullTextSession = Search.getFullTextSession(session);
  fullTextSession.setFlushMode(FlushMode.AUTO);
  fullTextSession.setCacheMode(CacheMode.IGNORE);
  try {
    BaseDO< ? > dbObj = (BaseDO< ? >) session.get(obj.getClass(), obj.getId());
    if (dbObj == null) {
      dbObj = (BaseDO< ? >) session.load(obj.getClass(), obj.getId());
    }
    fullTextSession.index(dbObj);
    alreadyReindexed.add(getReindexId(dbObj));
    if (log.isDebugEnabled() == true) {
      log.debug("Object added to index: " + getReindexId(dbObj));
    }
  } catch (final Exception ex) {
    // Don't fail if any exception while re-indexing occurs.
    log.info("Fail to re-index " + obj.getClass() + ": " + ex.getMessage());
  }
  // session.flush(); // clear every batchSize since the queue is processed
  final List<Entry> entryList = map.get(obj.getClass());
  reindexDependents(hibernateTemplate, session, obj, entryList, alreadyReindexed);
}
 
Example 15
private List< ? > getDependents(final HibernateTemplate hibernateTemplate, final RegistryEntry registryEntry, final Entry entry,
  final BaseDO< ? > obj)
  {
final String queryString;
if (entry.setOrCollection == true) {
  queryString = "from " + registryEntry.getDOClass().getName() + " o join o." + entry.fieldName + " r where r.id=?";
} else {
  queryString = "from " + registryEntry.getDOClass().getName() + " o where o." + entry.fieldName + ".id=?";
}
if (log.isDebugEnabled() == true) {
  log.debug(queryString + ", id=" + obj.getId());
}
final List< ? > result = hibernateTemplate.find(queryString, obj.getId());
return result;
  }
 
Example 16
private static void deleteFrom(final HibernateTemplate hibernateTemplate, final String entity)
{
  try {
    final Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery("delete from " + entity);
    query.executeUpdate();
    hibernateTemplate.flush();
  } catch (final Exception ex) {
    log.info("delete from " + entity + " failed (may-be OK). Trying to use HibernateTemplate.deleteAll(List) instead.");
    deleteAllDBObjects(hibernateTemplate, entity);
  }
}
 
Example 17
private static void deleteAllDBObjects(final HibernateTemplate hibernateTemplate, final String entity)
{
  final List< ? > all = hibernateTemplate.find("from " + entity + " o");
  if (all != null && all.size() > 0) {
    hibernateTemplate.deleteAll(all);
    hibernateTemplate.flush();
  }
}
 
Example 18
Source Project: icure-backend   Source File: DrugsDAOImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
protected HibernateTemplate getHibernateTemplate() {
	return new HibernateTemplate(getSessionFactory());
}
 
Example 19
Source Project: shiroDemo   Source File: BaseDao.java    License: Apache License 2.0 4 votes vote down vote up
public HibernateTemplate getTemplate() {
    if (template == null) {
        this.setTemplate(new HibernateTemplate(this.getSessionFactory()));
    }
    return template;
}
 
Example 20
Source Project: shiroDemo   Source File: BaseDao.java    License: Apache License 2.0 4 votes vote down vote up
public void setTemplate(HibernateTemplate template) {
    this.template = template;
}
 
Example 21
Source Project: xmu-2016-MrCode   Source File: BaseDaoImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
public HibernateTemplate getHibernateTemplate() {
	return hibernateTemplate;
}
 
Example 22
public void setSessionFactory(SessionFactory sessionFactory) {
	this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
 
Example 23
public void setSessionFactory(SessionFactory sessionFactory) {
	this.template = new HibernateTemplate(sessionFactory);
}
 
Example 24
Source Project: compass   Source File: HibernateAccountDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
public HibernateTemplate getMasterSlaveHibernateTemplate() {
	return masterSlaveHibernateTemplate;
}
 
Example 25
Source Project: compass   Source File: HibernateAccountDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
public void setMasterSlaveHibernateTemplate(
		HibernateTemplate masterSlaveHibernateTemplate) {
	this.masterSlaveHibernateTemplate = masterSlaveHibernateTemplate;
}
 
Example 26
Source Project: compass   Source File: ShardHibernatePlanDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
public HibernateTemplate getShardHibernateTemplate() {
	return shardHibernateTemplate;
}
 
Example 27
Source Project: compass   Source File: ShardHibernatePlanDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
public void setShardHibernateTemplate(HibernateTemplate shardHibernateTemplate) {
	this.shardHibernateTemplate = shardHibernateTemplate;
}
 
Example 28
Source Project: DataHubSystem   Source File: UserDao.java    License: GNU Affero General Public License v3.0 4 votes vote down vote up
public void cleanupTmpUser (int max_days)
{
   int skip = 0;
   final int top = DaoUtils.DEFAULT_ELEMENTS_PER_PAGE;
   long MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;
   long runtime = System.currentTimeMillis ();
   final String hql = "SELECT u, r FROM User u LEFT OUTER JOIN " +
      "u.restrictions r WHERE r.discriminator = 'temporary'";
   List<Object[]> result;
   HibernateTemplate template = getHibernateTemplate ();
   do
   {
      final int start = skip;
      result = template.execute (new HibernateCallback<List<Object[]>>()
      {
         @Override
         @SuppressWarnings ("unchecked")
         public List<Object[]> doInHibernate (Session session)
            throws HibernateException, SQLException
         {
            Query query = session.createQuery (hql).setReadOnly (true);
            query.setFirstResult (start);
            query.setMaxResults (top);
            return (List<Object[]>) query.list ();
         }
      });
      for (Object[] objects : result)
      {
         if (objects.length != 2) continue;
         
         User user = User.class.cast (objects[0]);
         TmpUserLockedAccessRestriction restriction = 
                  TmpUserLockedAccessRestriction.class.cast (objects[1]);
         
         long date = runtime - restriction.getLockDate ().getTime ();
         if ((date / MILLISECONDS_PER_DAY) >= max_days)
         {
            logger.info("Remove unregistered User " + user.getUsername ());
            forceDelete (user);
         }
      }
      skip = skip + top;
   }
   while (result.size () == top);
}
 
Example 29
Source Project: hrms   Source File: GenericDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
public HibernateTemplate getHibernateTemplate() {
	return hibernateTemplate;
}
 
Example 30
Source Project: hrms   Source File: GenericDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Resource
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
	this.hibernateTemplate = hibernateTemplate;
}