List of usage examples for org.hibernate Session clear
void clear();
From source file:gov.nih.nci.nbia.util.ProcessDicomObject.java
License:BSD License
public void process(List<Object[]> searchResults) { logger.info("start processing the result"); int commitSize = 0; DicomObject dicomObjectFile = null;//from ww w .j a v a 2s .co m Session s = getHibernateTemplate().getSessionFactory().openSession(); for (Object[] row : searchResults) { try { Integer giId = (Integer) row[0]; String dicomUri = (String) row[1]; File storedFile = new File(dicomUri); dicomObjectFile = new DicomObject(storedFile); Dataset set = dicomObjectFile.getDataset(); parseDICOMPropertiesFile(set); updateStoredDicomObject(s, giId); logger.info("MR Image: image pk Id:- " + giId + " dicomUri:- " + dicomUri); commitSize++; if (commitSize == rowsPerCommit) { logger.info("committing records.."); commitSize = 0; s.flush(); s.clear(); } } catch (Exception e) { s.clear(); logger.error(e); logger.info("continue processing"); } finally { if (dicomObjectFile != null) { dicomObjectFile.close(); } } } s.close(); }
From source file:gov.nih.nci.system.dao.impl.orm.ORMDAOImpl.java
License:Open Source License
/** * Return the resultset of the query embedded in an object of gov.nih.nci.common.net.Response * @param request - a gov.nih.nci.common.net.Request object passed from client * @return an object of gov.nih.nci.common.net.Response that contains the query resultset * @throws DAOException//w w w . ja v a2 s . com */ public Response query(Request request) throws DAOException { List rs = null; int counter = 0; ORMConnection ormConn = ORMConnection.getInstance(); org.hibernate.Session session = null; Criteria hCriteria = null; Integer rowCount = null; Query query = null; String entityName = request.getDomainObjectName(); ServiceLocator serviceLocator = null; try { serviceLocator = (ServiceLocator) ObjectFactory.getObject("ServiceLocator"); counter = serviceLocator.getORMCounter(entityName); session = ORMConnection.openSession(entityName); } catch (Exception e) { log.error("Could not retrieve proper datasource \n " + e.getMessage()); throw new DAOException("Could not retrieve proper datasource " + e); } Object obj = request.getRequest(); Integer firstRow = request.getFirstRow(); log.debug("Integer firstRow = " + firstRow); Integer resultsPerQuery = request.getRecordsCount(); log.debug("Integer resultsPerQuery = " + resultsPerQuery); Boolean isCount = request.getIsCount(); log.debug("boolean isCount = " + isCount.booleanValue()); getMaxRecordsPerQuery(); try { if (obj instanceof DetachedCriteria) { hCriteria = ((org.hibernate.criterion.DetachedCriteria) request.getRequest()) .getExecutableCriteria(session); log.info("Detached Criteria Query :" + hCriteria.toString()); callAuditAPIQuery(hCriteria.toString()); if (hCriteria != null) { if (isCount != null && isCount.booleanValue()) { rowCount = (Integer) hCriteria.setProjection(Projections.rowCount()).uniqueResult(); log.debug("DetachedCriteria ORMDAOImpl ===== count = " + rowCount); hCriteria.setResultTransformer(Criteria.ROOT_ENTITY); hCriteria.setProjection(null); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) hCriteria.setFirstResult(firstRow.intValue()); if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery; log.error(msg); throw new Exception(msg); } else { hCriteria.setMaxResults(resultsPerQuery.intValue()); } } else { hCriteria.setMaxResults(recordsPerQuery); }*/ // Set resultSet = new HashSet(hCriteria.list()); // rs = new ArrayList((Collection)resultSet); hCriteria.setMaxResults(maxRecordsPerQuery); rs = hCriteria.list(); } } } else if (obj instanceof NestedCriteria) { log.debug("ORMDAOImpl.query: it is a NestedCriteria Object ...."); System.out.println("Nested Criteria ~~~~~~~~~~~~~~~" + ((NestedCriteria) obj).getRoleName()); if (((NestedCriteria) obj).getRoleName() == null) { ((NestedCriteria) obj).setRoleName(""); } System.out.println("config: " + ormConn.getConfiguration(counter)); NestedCriteria2HQL converter = new NestedCriteria2HQL((NestedCriteria) obj, ormConn.getConfiguration(counter), session); query = converter.translate(); log.info("HQL Query :" + query.getQueryString()); callAuditAPIQuery(query.getQueryString()); if (query != null) { if (isCount != null && isCount.booleanValue()) { log.debug("ORMDAOImpl. isCount .... .... | converter.getCountQuery() = " + converter.getCountQuery().getQueryString()); rowCount = (Integer) converter.getCountQuery().uniqueResult(); log.debug("ORMDAOImpl HQL ===== count = " + rowCount); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) { log.debug("Setting First Row to " + firstRow); query.setFirstResult(firstRow.intValue()); } if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ; log.error(msg); throw new Exception(msg); } else { log.debug("Setting Max Results to " + resultsPerQuery.intValue()); query.setMaxResults(resultsPerQuery.intValue()); } } else { log.debug("Setting Max Results to " + recordsPerQuery); query.setMaxResults(recordsPerQuery); }*/ query.setMaxResults(maxRecordsPerQuery); rs = query.list(); } } } else if (obj instanceof HQLCriteria) { Query hqlQuery = null; boolean isQueryFromGrid = isQueryFromGrid((HQLCriteria) obj); if (isQueryFromGrid) { hqlQuery = session.createQuery(modifiyQueryFromGrid(((HQLCriteria) obj).getHqlString())); } else { hqlQuery = session.createQuery(((HQLCriteria) obj).getHqlString()); } log.info("HQL Criteria Query :" + hqlQuery.getQueryString()); callAuditAPIQuery(hqlQuery.getQueryString()); if (isCount != null && isCount.booleanValue()) { rowCount = new Integer(hqlQuery.list().size()); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) { hqlQuery.setFirstResult(firstRow.intValue()); } if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ; log.error(msg); throw new Exception(msg); } else { hqlQuery.setMaxResults(resultsPerQuery.intValue()); } } else { hqlQuery.setMaxResults(maxRecordsPerQuery); }*/ hqlQuery.setMaxResults(maxRecordsPerQuery); rs = hqlQuery.list(); if (isQueryFromGrid) { rs = createObjectList(ormConn.getConfiguration(counter).getClassMapping(entityName), entityName, rs); } } } else if (obj instanceof CQLQuery) { HibernateQueryWrapper queryWrapper = CQL2HQL.translate((CQLQuery) obj, false, request.getCaseSensitivity().booleanValue()); String hql = queryWrapper.getHql(); List params = queryWrapper.getParameters(); log.info("CQL Query :" + hql); callAuditAPIQuery(hql); Query hqlQuery = session.createQuery(hql); for (int i = 0; i < params.size(); i++) hqlQuery.setParameter(i, params.get(i)); if (isCount != null && isCount.booleanValue()) { rowCount = new Integer(hqlQuery.list().size()); } else if ((isCount != null && !isCount.booleanValue()) || isCount == null) { /* if(firstRow != null) { hqlQuery.setFirstResult(firstRow.intValue()); } if(resultsPerQuery != null) { if(resultsPerQuery.intValue() > maxRecordsPerQuery) { String msg = "Illegal Value for RecordsPerQuery: recordsPerQuery cannot be greater than maxRecordsPerQuery. RecordsPerQuery = " + recordsPerQuery + " maxRecordsPerQuery = " + maxRecordsPerQuery ; log.error(msg); throw new Exception(msg); } else { hqlQuery.setMaxResults(resultsPerQuery.intValue()); } } else { hqlQuery.setMaxResults(maxRecordsPerQuery); }*/ hqlQuery.setMaxResults(maxRecordsPerQuery); rs = hqlQuery.list(); } } } catch (JDBCException ex) { log.error("JDBC Exception in ORMDAOImpl ", ex); throw new DAOException("JDBC Exception in ORMDAOImpl ", ex); } catch (org.hibernate.HibernateException hbmEx) { log.error(hbmEx.getMessage()); throw new DAOException("Hibernate problem ", hbmEx); } catch (Exception e) { log.error("Exception ", e); throw new DAOException("Exception in the ORMDAOImpl ", e); } finally { try { session.clear(); session.close(); } catch (Exception eSession) { log.error("Could not close the session - " + eSession.getMessage()); throw new DAOException("Could not close the session " + eSession); } } Response rsp = new Response(); if (isCount != null && isCount.booleanValue()) rsp.setRowCount(rowCount); else rsp.setResponse(rs); return rsp; }
From source file:hibernate.DatabaseFacade.java
License:Open Source License
/** * close the hibernateSession to database, and relase the connection. * Clear the content before closing the session. * /* ww w.ja v a 2 s .co m*/ * @param the hibernateSession to close */ public static void closeDBSession(Session hibernateSession) { log.trace("Starting to close hibernateSession " + hibernateSession.hashCode()); if (hibernateSession != null) { if (hibernateSession.isConnected() && hibernateSession.isOpen()) { hibernateSession.clear(); hibernateSession.close(); } else { log.error("Cannot close hibernateSession"); } } }
From source file:info.jtrac.hibernate.HibernateJtracDao.java
License:Apache License
public List<Item> findItems(ItemSearch itemSearch) { int pageSize = itemSearch.getPageSize(); // TODO: if we are ordering by a custom column, we must load the whole // list to do an in-memory sort. we need to find a better way Field.Name sortFieldName = Field.isValidName(itemSearch.getSortFieldName()) ? Field.convertToName(itemSearch.getSortFieldName()) : null;/*from www . ja va 2 s . c om*/ // only trigger the in-memory sort for drop-down fields and when querying within a space // UI currently does not allow you to sort by custom field when querying across spaces, but check again boolean doInMemorySort = sortFieldName != null && sortFieldName.isDropDownType() && itemSearch.getSpace() != null; if (pageSize == -1 || doInMemorySort) { List<Item> list = getHibernateTemplate().findByCriteria(itemSearch.getCriteria()); if (!list.isEmpty() && doInMemorySort) { doInMemorySort(list, itemSearch); } itemSearch.setResultCount(list.size()); if (pageSize != -1) { // order-by was requested on custom field, so we loaded all results, but only need one page int start = pageSize * itemSearch.getCurrentPage(); int end = Math.min(start + itemSearch.getPageSize(), list.size()); return list.subList(start, end); } return list; } else { // pagination if (itemSearch.isBatchMode()) { getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) { session.clear(); return null; } }); } int firstResult = pageSize * itemSearch.getCurrentPage(); List<Item> list = getHibernateTemplate().findByCriteria(itemSearch.getCriteria(), firstResult, pageSize); if (!itemSearch.isBatchMode()) { DetachedCriteria criteria = itemSearch.getCriteriaForCount(); criteria.setProjection(Projections.rowCount()); Integer count = (Integer) getHibernateTemplate().findByCriteria(criteria).get(0); itemSearch.setResultCount(count); } return list; } }
From source file:info.jtrac.hibernate.HibernateJtracDao.java
License:Apache License
public List<Item> findAllItems(final int firstResult, final int batchSize) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) { session.clear(); Criteria criteria = session.createCriteria(Item.class); criteria.setCacheMode(CacheMode.IGNORE); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.setFetchMode("history", FetchMode.JOIN); criteria.add(Restrictions.ge("id", (long) firstResult)); criteria.add(Restrictions.lt("id", (long) firstResult + batchSize)); return criteria.list(); }/*from ww w.j a va 2 s. c o m*/ }); }
From source file:isjexecact.br.com.inso.Funcionalidades.CriarTarefaCompromisso.TarefaCompromissos.java
public void criarTarefaCompromisso() throws Exception { // Validao bsica Valida();/*from ww w. jav a2 s . c o m*/ // Abertura da sesso e do controle de transao SessionFactory sessionFactory = HibernateUtil.getSessionFactory(null); Session sessao = sessionFactory.openSession(); Transaction tx = sessao.beginTransaction(); // Persistir a tarefa / compromisso TarefaCompromisso tc = atribuirTarefaCompromisso(); TarefaCompromissoDAOHibernate daotc = new TarefaCompromissoDAOHibernate(); daotc.setSession(sessao); daotc.inserirRegistro(tc); // Persistir participantes persistirParticipantes(tc, sessao); // Persistir responsaveis persistirResponsaveis(tc, sessao); // Persistir referencia persistirReferencia(tc, sessao); // Persistir lembretes persistirLembretes(tc, sessao); // Persistir lembretes dos logins persistirLoginLembrete(tc, sessao); // Otmizando o cache da session, melhorando a utilizao da memria sessao.flush(); sessao.clear(); tx.commit(); sessao.close(); // Verifica se esta configurado para enviar e-mail para participantes e responsveis if (FlEmailPart.toUpperCase().equals("S") || FlEmailResp.toUpperCase().equals("S")) { EnviaEmail(); } }
From source file:jshm.dataupdaters.GhSongUpdater.java
License:Open Source License
@SuppressWarnings("unchecked") public static void updateSongInfo(final ResultProgressHandle progress, GhGameTitle ttl) throws Exception { if (null != progress) progress.setBusy("Downloading song meta data..."); GhSongInfoFetcher fetcher = new GhSongInfoFetcher(); fetcher.fetch(ttl);// w ww .j a va 2s . c o m Session session = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); int i = 0, total = fetcher.songMap.size(); for (String key : fetcher.songMap.keySet()) { if (null != progress) progress.setProgress(String.format("Processing song %s of %s", i + 1, total), i, total); String upperTtl = key.toUpperCase(); List<GhSong> result = (List<GhSong>) session .createQuery("FROM GhSong WHERE game LIKE :gameTtl AND UPPER(title) LIKE :ttl") .setString("gameTtl", ttl.title + "_%").setString("ttl", upperTtl).list(); LOG.finer("result.size() == " + result.size()); for (GhSong s : result) { if (s.update(fetcher.songMap.get(key))) { LOG.info("Updating song to: " + s); session.update(s); } else { LOG.finer("No changes to song: " + s); } } if (i % 64 == 0) { session.flush(); session.clear(); } i++; } tx.commit(); } catch (HibernateException e) { if (null != tx && tx.isActive()) tx.rollback(); LOG.throwing("GhSongUpdater", "updateSongInfo", e); throw e; } finally { if (null != session && session.isOpen()) session.close(); } ttl.initDynamicTiers(); }
From source file:jshm.dataupdaters.RbSongUpdater.java
License:Open Source License
public static void updateViaXml(final ResultProgressHandle progress, final GameTitle game) throws Exception { if (!(game instanceof RbGameTitle)) throw new IllegalArgumentException("game must be an RbGameTitle"); Session session = null; Transaction tx = null;// w w w. j a v a 2 s.c om try { session = openSession(); tx = session.beginTransaction(); // first get the songs themselves if (null != progress) progress.setBusy("Downloading song data for " + game); RbSongDataFetcher fetcher = new RbSongDataFetcher(); fetcher.fetch((RbGameTitle) game); LOG.finer("xml updated at " + fetcher.updated); Map<RbGame, Tiers> tiers = fetcher.tierMap; LOG.finer("xml had " + tiers.size() + " tiers for " + game); if (null != progress) progress.setBusy("Updating tiers"); for (RbGame key : tiers.keySet()) { Tiers.setTiers(key, tiers.get(key)); key.mapTiers(tiers.get(key)); } Tiers.write(); List<RbSong> songs = fetcher.songs; LOG.finer("xml had " + songs.size() + " songs for " + game); if (songs.isEmpty()) { throw new Exception("xml had 0 songs for " + game + ", it's probably out of date"); } int i = 0, total = songs.size(); for (RbSong song : songs) { if (null != progress) progress.setProgress(String.format("Processing song %s of %s", i + 1, total), i, total); // only care about the sh id and gameTitle RbSong result = (RbSong) session .createQuery("FROM RbSong WHERE scoreHeroId=:shid AND gameTitle=:gameTtl") .setInteger("shid", song.getScoreHeroId()).setString("gameTtl", song.getGameTitle().title) .uniqueResult(); if (null == result) { // new insert LOG.info("Inserting song: " + song); session.save(song); } else { LOG.finest("found song: " + result); // update existing if (result.update(song, true)) { LOG.info("Updating song to: " + result); session.update(result); } else { LOG.finest("No changes to song: " + result); } } if (i % 64 == 0) { session.flush(); session.clear(); } i++; } // now get song orders List<SongOrder> orders = fetcher.orders; LOG.finer("xml had " + orders.size() + " song orderings for " + game); // faster to delete them all and insert instead of checking // each one separately LOG.info("Deleting old song orders"); int deletedOrderCount = session.createQuery("delete SongOrder where gameTitle=:gameTitle") .setString("gameTitle", game.toString()).executeUpdate(); LOG.finer("deleted " + deletedOrderCount + " old song orders"); i = 0; total = orders.size(); for (SongOrder order : orders) { // we need to get an instance of the RbSong that's in the db, // not the detached one we used before from the xml order.setSong(RbSong.getByScoreHeroId(session, order.getSong().getScoreHeroId())); // new insert LOG.info("Inserting song order: " + order); session.save(order); if (i % 64 == 0) { session.flush(); session.clear(); if (null != progress) progress.setProgress("Processing song order lists...", i, total); } i++; } tx.commit(); } catch (HibernateException e) { if (null != tx && tx.isActive()) tx.rollback(); LOG.throwing("RbSongUpdater", "updateViaXml", e); throw e; } finally { if (null != session && session.isOpen()) session.close(); } }
From source file:jshm.dataupdaters.RbSongUpdater.java
License:Open Source License
public static void updateViaScraping(final ResultProgressHandle progress, final GameTitle game) throws Exception { if (!(game instanceof RbGameTitle)) throw new IllegalArgumentException("game must be an RbGameTitle"); Session session = null; Transaction tx = null;/*w w w. j a v a2 s .c o m*/ try { session = openSession(); tx = session.beginTransaction(); // first get the songs themselves, need to do for each platform for (Game g : Game.getByTitle(game)) { if (null != progress) progress.setBusy("Downloading song list for " + g); List<RbSong> songs = RbSongScraper.scrape((RbGame) g); LOG.finer("scraped " + songs.size() + " songs for " + g); assert null != RbSongScraper.lastScrapedTiers; LOG.finer("remapping " + RbSongScraper.lastScrapedTiers.size() + " tiers for " + g); Tiers tiers = new Tiers(RbSongScraper.lastScrapedTiers); Tiers.setTiers(g, tiers); ((RbGame) g).mapTiers(tiers); int i = 0, total = songs.size(); for (RbSong song : songs) { if (null != progress) progress.setProgress(String.format("Processing song %s of %s", i + 1, total), i, total); // only care about the sh id and gameTitle RbSong result = (RbSong) session .createQuery("FROM RbSong WHERE scoreHeroId=:shid AND gameTitle=:gameTtl") .setInteger("shid", song.getScoreHeroId()) .setString("gameTtl", song.getGameTitle().title).uniqueResult(); if (null == result) { // new insert LOG.info("Inserting song: " + song); session.save(song); } else { LOG.finest("found song: " + result); // update existing if (result.update(song, false)) { LOG.info("Updating song to: " + result); session.update(result); } else { LOG.finest("No changes to song: " + result); } } if (i % 64 == 0) { session.flush(); session.clear(); } i++; } } // need to save tiers at some point Tiers.write(); // faster to delete them all and insert instead of checking // each one separately LOG.info("Deleting old song orders"); int deletedOrderCount = session.createQuery("delete SongOrder where gameTitle=:gameTitle") .setString("gameTitle", game.toString()).executeUpdate(); LOG.finer("deleted " + deletedOrderCount + " old song orders"); // for now we kind of have to do each platform/group combo.... 20+ requests ugh // at least it seems to be working for (Game g : Game.getByTitle(game)) { if (null != progress) progress.setBusy("Downloading song order lists for " + g); List<SongOrder> orders = RbSongScraper.scrapeOrders(progress, (RbGame) g); LOG.finer("scraped " + orders.size() + " song orderings for " + g); int i = 0, total = orders.size(); for (SongOrder order : orders) { LOG.info("Inserting song order: " + order); session.save(order); if (i % 64 == 0) { session.flush(); session.clear(); if (null != progress) progress.setProgress("Processing song order lists...", i, total); } i++; } } tx.commit(); } catch (HibernateException e) { if (null != tx && tx.isActive()) tx.rollback(); LOG.throwing("RbSongUpdater", "updateViaScraping", e); throw e; } finally { if (null != session && session.isOpen()) session.close(); } }