Example usage for org.hibernate Session doWork

List of usage examples for org.hibernate Session doWork

Introduction

In this page you can find the example usage for org.hibernate Session doWork.

Prototype

void doWork(Work work) throws HibernateException;

Source Link

Document

Controller for allowing users to perform JDBC related work using the Connection managed by this Session.

Usage

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private void readDetailsFromConnection(RepositoryDiag diag, final SqlRepositoryConfiguration config) {
    final List<LabeledString> details = diag.getAdditionalDetails();

    Session session = getSessionFactory().openSession();
    try {//w w w  . j ava  2  s  .c o m
        session.beginTransaction();
        session.doWork(new Work() {

            @Override
            public void execute(Connection connection) throws SQLException {
                details.add(new LabeledString(DETAILS_TRANSACTION_ISOLATION,
                        getTransactionIsolation(connection, config)));

                Properties info = connection.getClientInfo();
                if (info == null) {
                    return;
                }

                for (String name : info.stringPropertyNames()) {
                    details.add(new LabeledString(DETAILS_CLIENT_INFO + name, info.getProperty(name)));
                }
            }
        });
        session.getTransaction().commit();

        if (!(getSessionFactory() instanceof SessionFactoryImpl)) {
            return;
        }
        SessionFactoryImpl factory = (SessionFactoryImpl) getSessionFactory();
        // we try to override configuration which was read from sql repo configuration with
        // real configuration from session factory
        String dialect = factory.getDialect() != null ? factory.getDialect().getClass().getName() : null;
        details.add(new LabeledString(DETAILS_HIBERNATE_DIALECT, dialect));
    } catch (Throwable th) {
        //nowhere to report error (no operation result available)
        session.getTransaction().rollback();
    } finally {
        cleanupSessionAndResult(session, null);
    }
}

From source file:com.googlecode.sarasvati.hib.util.SarasvatiSchemaTool.java

License:Open Source License

public void executeDDL(final Session session, final String[] ddl) {
    session.doWork(new Work() {
        @Override//from   w ww  .  ja  v a2  s  .  c om
        public void execute(final Connection connection) throws SQLException {
            Statement stmt = connection.createStatement();

            try {
                for (String ddlStmt : ddl) {
                    System.out.println("DDL: " + ddlStmt);
                    stmt.execute(ddlStmt);
                }
            } finally {
                stmt.close();
            }
        }
    });
}

From source file:com.gramercysoftware.persistence.util.JpaJdbcConnectionJoiner.java

License:Open Source License

public void doWork(final JdbcWork<T> jdbcWork) {
    exception = null;/*from  w  w  w  . jav  a  2  s .c  o  m*/
    Session session = null;

    if (entityManager instanceof GSPEntityManager) {
        session = ((HibernateEntityManager) ((GSPEntityManager) entityManager).getWrappedEntityManager())
                .getSession();
    } else {
        session = ((HibernateEntityManager) entityManager).getSession();
    }

    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            try {
                response = jdbcWork.execute(connection);
            } catch (SQLException sqlex) {
                throw sqlex;
            } catch (Exception t) {
                exception = t;
            }
        }
    });

    if (exception != null) {
        throw new RuntimeException(exception);
    }
}

From source file:com.hmsinc.epicenter.model.util.ModelUtils.java

License:Open Source License

/**
 * Disables "nested loops" optimization on PostgreSQL. This is needed with
 * various spatial queries that confuse the optimizer.
 * /*w w w.  j a v  a  2  s . c om*/
 * @param entityManager
 */
public static void disableNestedLoops(final EntityManager entityManager) {

    final Session s = (Session) entityManager.getDelegate();
    final SessionFactoryImpl sf = (SessionFactoryImpl) s.getSessionFactory();
    if (sf.getDialect() instanceof PostgreSQLDialect) {
        s.doWork(new Work() {
            public void execute(Connection conn) throws SQLException {
                conn.createStatement().execute("set enable_nestloop=off");
            }

        });
    }
}

From source file:com.hmsinc.epicenter.model.util.ModelUtils.java

License:Open Source License

/**
 * Enables "nested loops" optimization on PostgreSQL. This is needed with
 * various spatial queries that confuse the optimizer.
 * /*from   w ww.ja v a  2 s  . c  o  m*/
 * @param entityManager
 */
public static void enableNestedLoops(final EntityManager entityManager) {

    final Session s = (Session) entityManager.getDelegate();
    final SessionFactoryImpl sf = (SessionFactoryImpl) s.getSessionFactory();
    if (sf.getDialect() instanceof PostgreSQLDialect) {
        s.doWork(new Work() {
            public void execute(Connection conn) throws SQLException {
                conn.createStatement().execute("set enable_nestloop=on");
            }

        });
    }
}

From source file:com.ikon.dao.HibernateUtil.java

License:Open Source License

/**
 * Load specific database import// w  w w  . j av  a 2 s. c  om
 */
private static void executeImport(final Reader rd) {
    Session session = null;
    Transaction tx = null;

    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        session.doWork(new Work() {
            @Override
            public void execute(Connection con) throws SQLException {
                try {
                    for (HashMap<String, String> error : LegacyDAO.executeScript(con, rd)) {
                        log.error("Error during import script execution at line {}: {} [ {} ]",
                                new Object[] { error.get("ln"), error.get("msg"), error.get("sql") });
                    }
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    IOUtils.closeQuietly(rd);
                }
            }
        });

        commit(tx);
    } catch (Exception e) {
        rollback(tx);
        log.error(e.getMessage(), e);
    }
}

From source file:com.ikon.servlet.admin.ConfigServlet.java

License:Open Source License

/**
 * Import configuration into database//from w w w.j av  a2 s  . c o  m
 */
private void importConfig(String userId, HttpServletRequest request, HttpServletResponse response,
        final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException {
    log.debug("importConfig({}, {}, {}, {}, {})", new Object[] { userId, request, response, data, dbSession });
    WorkerUpdate worker = new DatabaseQueryServlet().new WorkerUpdate();
    worker.setData(data);
    dbSession.doWork(worker);
    log.debug("importConfig: void");
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

License:Open Source License

/**
 * Execute JDBC query/*from  w w w .ja  va2 s  .c  o m*/
 */
private void executeJdbc(Session session, String qs, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    WorkerJdbc worker = new WorkerJdbc();
    worker.setQueryString(qs);
    session.doWork(worker);

    //sc.setAttribute("sql", null);
    sc.setAttribute("exception", null);
    sc.setAttribute("globalResults", worker.getGlobalResults());
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

License:Open Source License

/**
 * Import into database/*from   w  ww . ja v a 2 s.co m*/
 */
private void executeUpdate(Session session, byte[] data, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, ServletException, IOException {
    log.debug("executeUpdate({}, {}, {})", new Object[] { session, request, response });
    List<GlobalResult> globalResults = new ArrayList<DatabaseQueryServlet.GlobalResult>();
    WorkerUpdate worker = new WorkerUpdate();
    worker.setData(data);
    session.doWork(worker);

    GlobalResult gr = new GlobalResult();
    gr.setColumns(null);
    gr.setResults(null);
    gr.setSql(null);
    gr.setRows(worker.getRows());
    gr.setErrors(worker.getErrors());
    globalResults.add(gr);

    sc.setAttribute("qs", null);
    sc.setAttribute("type", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);

    log.debug("executeUpdate: void");
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

License:Open Source License

/**
 * List tables from database// w  w w . ja va2  s  . c o  m
 */
private List<String> listTables(Session session) {
    final List<String> tables = new ArrayList<String>();
    final String[] tableTypes = { "TABLE" };
    final String[] tablePatterns = new String[] { "JBPM_%", "OKM_%", "DEFAULT_%", "VERSION_%", "jbpm_%",
            "okm_%", "default_%", "version_%" };

    session.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            DatabaseMetaData md = con.getMetaData();

            for (String table : tablePatterns) {
                ResultSet rs = md.getTables(null, null, table, tableTypes);

                while (rs.next()) {
                    tables.add(rs.getString(3));
                }

                rs.close();
            }
        }
    });

    return tables;
}