List of usage examples for org.hibernate Session doWork
void doWork(Work work) throws HibernateException;
From source file:org.n52.sos.web.admin.AbstractAdminController.java
License:Open Source License
private void executeSqlFile(String path) throws SQLException, FileNotFoundException, ConnectionProviderException { final File f = new File(getContext().getRealPath(path)); if (!f.exists()) { throw new FileNotFoundException(f.getAbsolutePath() + " not found."); }//from w ww . j a va 2 s. c om ConnectionProvider p = Configurator.getInstance().getDataConnectionProvider(); Object con = null; try { con = p.getConnection(); if (con instanceof Connection) { try { SQLHelper.executeSQLFile((Connection) con, f); } catch (IOException ex) { throw new SQLException(ex); } } else if (con instanceof Session) { Session s = (Session) con; Transaction t = s.beginTransaction(); try { s.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { try { SQLHelper.executeSQLFile(connection, f); } catch (IOException ex) { throw new SQLException(ex); } } }); t.commit(); } catch (HibernateException e) { t.rollback(); } } else { throw new SQLException("Unknown conncetion type: " + con.getClass()); } } finally { p.returnConnection(con); } }
From source file:org.openmrs.module.openhmis.plm.db.DatabaseListProvider.java
License:Open Source License
/** * Adds a new item to the list./* w ww.j a v a 2 s .co m*/ * @param item The item to add. * @should add the item to the database * @should correctly update the index of the other items in the table * @should throw PersistentListException when the command returns 0 rows updated * @should roll back the transaction when the operation fails * @shold commit the transaction if no operations fail */ @Override public void add(final PersistentListItemModel item) { Session session = sessionFactory.getCurrentSession(); Transaction trans = null; try { // Start transaction trans = session.beginTransaction(); // Update all items >= index to be their current index + 1 // TODO: Can this type of query be handled by Hibernate without needing to use hardcoded SQL? session.doWork(new Work() { public void execute(Connection connection) { try { PreparedStatement cmd = connection.prepareStatement(ADD_SQL); cmd.setInt(1, item.getListId()); cmd.setInt(2, item.getItemOrder()); cmd.executeUpdate(); } catch (SQLException sex) { throw new PersistentListException(sex); } } }); // Insert item with index session.save(item); session.flush(); // Commit transaction trans.commit(); } catch (Exception ex) { log.debug("The list add operation failed. Rolling back transaction..."); trans.rollback(); log.debug("Transaction rolled back."); throw new PersistentListException("An exception occurred while attempting to add the item to the list.", ex); } finally { session.close(); } }
From source file:org.openmrs.module.openhmis.plm.db.DatabaseListProvider.java
License:Open Source License
/** * Removes the specified item from the list. * @param item The item to remove.// w w w . j av a2 s .co m * @return {@code true} if the item was removed; otherwise, {@code false}. */ @Override public boolean remove(final PersistentListItemModel item) { Session session = sessionFactory.getCurrentSession(); Transaction trans = null; try { // Start transaction trans = session.beginTransaction(); // Delete item with index session.delete(item); session.flush(); // Update all items >= index to be their current index - 1 // TODO: Can this type of query be handled by Hibernate without needing to use hardcoded SQL? session.doWork(new Work() { public void execute(Connection connection) { try { PreparedStatement cmd = connection.prepareStatement(REMOVE_SQL); cmd.setInt(1, item.getListId()); cmd.setInt(2, item.getItemOrder()); cmd.executeUpdate(); } catch (SQLException sex) { throw new PersistentListException(sex); } } }); // Commit transaction trans.commit(); } catch (Exception ex) { log.error("The list item delete operation failed. Rolling back transaction...", ex); trans.rollback(); log.debug("Transaction rolled back."); throw new PersistentListException( "An exception occurred while attempting to delete the item from the list.", ex); } finally { session.close(); } return true; }
From source file:org.openmrs.module.openhmis.plm.db.DatabaseListProvider.java
License:Open Source License
/** * Removes all items from the specified list. * @param list The list to clear./*w w w . j a v a 2 s .co m*/ */ @Override public void clear(final PersistentList list) { Session session = sessionFactory.getCurrentSession(); try { // Delete all items with list key session.doWork(new Work() { public void execute(Connection connection) { try { PreparedStatement cmd = connection.prepareStatement(CLEAR_SQL); cmd.setInt(1, list.getId()); cmd.executeUpdate(); } catch (SQLException sex) { throw new PersistentListException(sex); } } }); } catch (Exception ex) { throw new PersistentListException("An exception occurred while attempting to get the list items.", ex); } finally { session.close(); } }
From source file:org.openmrs.util.DatabaseUtil.java
License:Mozilla Public License
/** * Executes the passed SQL query, enforcing select only if that parameter is set for given Session *//*from ww w. j a v a 2 s . c o m*/ public static List<List<Object>> executeSQL(Session session, String sql, boolean selectOnly) throws DAOException { sql = sql.trim(); boolean dataManipulation = checkQueryForManipulationCommands(sql, selectOnly); final List<List<Object>> result = new ArrayList<List<Object>>(); final String query = sql; final boolean sessionDataManipulation = dataManipulation; //todo replace with lambdas after moving on to Java 8 session.doWork(new Work() { @Override public void execute(Connection conn) { populateResultsFromSQLQuery(conn, query, sessionDataManipulation, result); } }); return result; }
From source file:org.phenotips.tool.utils.XContextFactory.java
License:Open Source License
/** * Shuts down HSQLDB./*from w w w .ja v a 2 s . c om*/ * * @param context the XWiki Context object from which we can retrieve the Store implementation */ private static void shutdownHSQLDB(XWikiContext context) { XWikiStoreInterface store = context.getWiki().getStore(); if (XWikiCacheStore.class.isAssignableFrom(store.getClass())) { store = ((XWikiCacheStore) store).getStore(); } if (XWikiHibernateStore.class.isAssignableFrom(store.getClass())) { XWikiHibernateStore hibernateStore = (XWikiHibernateStore) store; // check that is HSQLDB Dialect dialect = Dialect.getDialect(hibernateStore.getConfiguration().getProperties()); if (!(dialect instanceof HSQLDialect)) { return; } try { hibernateStore.checkHibernate(context); hibernateStore.executeRead(context, new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException, XWikiException { session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); stmt.execute("SHUTDOWN"); } }); return null; } }); } catch (Exception e) { // This shouldn't matter so much } } }
From source file:org.sigmah.server.dao.hibernate.LoadDataSet.java
License:Open Source License
private void executeOperation(final DatabaseOperation op, final IDataSet dataSet) { HibernateEntityManager hem = (HibernateEntityManager) emf.createEntityManager(); Session session = hem.getSession(); session.doWork(new Work() { @Override/* www . ja v a 2s . c o m*/ public void execute(Connection connection) throws SQLException { try { IDatabaseConnection dbUnitConnection = createDbUnitConnection(connection); op.execute(dbUnitConnection, dataSet); } catch (DatabaseUnitException e) { throw new RuntimeException(e); } } }); hem.close(); }
From source file:org.ualerts.testing.jpa.HibernatePersistentDataResource.java
License:Apache License
/** * {@inheritDoc}//from w w w .j a v a2 s.com */ @Override protected void doExecuteSQL(EntityManager entityManager, URL resource) throws Throwable { logger.info("processing resource: {}", resource); Session session = (Session) entityManager.getDelegate(); final String[] sqlStatements = loadSQLStatements(resource); logger.debug("loaded {} statements", sqlStatements.length); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = connection.createStatement(); int count = 0; try { for (int i = 0; i < sqlStatements.length; i++) { logger.debug("executing: {}", sqlStatements[i].replaceAll("\n", "")); statement.execute(sqlStatements[i]); count++; } } finally { statement.close(); logger.info("executed {} statements", count); } } }); }
From source file:org.unitime.commons.hibernate.util.DatabaseUpdate.java
License:Open Source License
public boolean performUpdate(Element updateElement) { int version = Integer.parseInt(updateElement.attributeValue("version")); Session hibSession = new _RootDAO().getSession(); String schema = _RootDAO.getConfiguration().getProperty("default_schema"); Transaction tx = null;/*from ww w .j av a 2 s .co m*/ Hashtable variables = new Hashtable(); try { tx = hibSession.beginTransaction(); sLog.info(" Performing " + updateName() + " update to version " + version + " (" + updateElement.attributeValue("comment") + ")"); for (Iterator i = updateElement.elementIterator(); i.hasNext();) { Element queryElement = (Element) i.next(); String type = queryElement.getName(); String query = queryElement.getText().trim().replaceAll("%SCHEMA%", schema); for (Iterator j = variables.entrySet().iterator(); j.hasNext();) { Map.Entry entry = (Map.Entry) j.next(); query = query.replaceAll("%" + entry.getKey() + "%", entry.getValue().toString()); } String condition = queryElement.attributeValue("condition", "none"); String action = queryElement.attributeValue("action", "next"); String value = queryElement.attributeValue("value"); String into = queryElement.attributeValue("into"); if (queryElement.attribute("onFail") != null) { condition = "fail"; action = queryElement.attributeValue("onFail"); } if (queryElement.attribute("onEqual") != null) { condition = "equal"; action = queryElement.attributeValue("onEqual"); } if (queryElement.attribute("onNotEqual") != null) { condition = "notEqual"; action = queryElement.attributeValue("onNotEqual"); } if (query.length() == 0) continue; try { if (type.equals("hql") || type.equals("sql") || type.equals(iDialectSQL)) { sLog.debug(" -- HQL: " + query + " (con:" + condition + ", act:" + action + ", val:" + value + ")"); Query q = null; try { q = (type.equals("hql") ? hibSession.createQuery(query) : hibSession.createSQLQuery(query)); } catch (QueryException e) { // Work-around Hibernate issue HHH-2697 (https://hibernate.onjira.com/browse/HHH-2697) if (!"hql".equals(type)) { final String sql = query; hibSession.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = connection.createStatement(); int lines = statement.executeUpdate(sql); sLog.debug(" -- " + lines + " lines affected."); statement.close(); } }); } else throw e; } boolean ok = true; if (into != null) { variables.put(into, q.uniqueResult().toString()); } else if ("equal".equals(condition) && value != null) { ok = value.equals(q.uniqueResult().toString()); } else if ("notEqual".equals(condition) && value != null) { ok = !value.equals(q.uniqueResult().toString()); } else if (q != null) { int lines = q.executeUpdate(); sLog.debug(" -- " + lines + " lines affected."); if ("noChange".equals(condition)) ok = (lines == 0); else if ("change".equals(condition)) ok = (lines > 0); } if (ok) { if ("next".equals(action)) continue; if ("done".equals(action)) break; if ("fail".equals(action)) { sLog.error("Update to " + updateName() + " version " + version + " failed (condition not met for query '" + query + "', con:" + condition + ", act:" + action + ", val:" + value + ")."); tx.rollback(); return false; } } } else { sLog.debug(" -- skip: " + query + " (con:" + condition + ", act:" + action + ", val:" + value + ")"); } } catch (Exception e) { sLog.warn("Query '" + query + "' failed, " + e.getMessage(), e); if (e.getCause() != null && e.getCause().getMessage() != null) sLog.warn("Cause: " + e.getCause().getMessage()); if ("fail".equals(condition)) { if ("next".equals(action)) continue; if ("done".equals(action)) break; } sLog.error("Update to version " + version + " failed."); tx.rollback(); return false; } } ApplicationConfig versionCfg = ApplicationConfig.getConfig(versionParameterName()); if (versionCfg == null) { versionCfg = new ApplicationConfig(versionParameterName()); versionCfg.setDescription("Timetabling " + updateName() + " DB version (do not change -- this is used by automatic database update)"); } versionCfg.setValue(String.valueOf(version)); hibSession.saveOrUpdate(versionCfg); sLog.info(" " + updateName() + " Database version increased to: " + version); if (tx != null && tx.isActive()) tx.commit(); HibernateUtil.clearCache(); return true; } catch (Exception e) { if (tx != null && tx.isActive()) tx.rollback(); sLog.error("Update to version " + version + " failed, reason:" + e.getMessage(), e); return false; } }
From source file:org.zht.framework.zhtdao.hibernate.impl.HibernateBaseDaoImpl.java
License:Apache License
@Override public void executeUpdateSqlStatement(final String sql) throws DaoException { Session session = this.getCurrentSession(); session.doWork(new Work() { public void execute(Connection conn) throws SQLException { try { PreparedStatement ps = conn.prepareStatement(sql); ps.executeUpdate();// w w w . j a va2 s . c o m } catch (Exception e) { e.printStackTrace(); } } }); }