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.ikon.servlet.admin.LanguageServlet.java

License:Open Source License

/**
 * Import a new language into database/*  w  ww .j  a v  a  2s.co m*/
 */
private void importLanguage(String userId, HttpServletRequest request, HttpServletResponse response,
        final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException {
    log.debug("importLanguage({}, {}, {}, {}, {})",
            new Object[] { userId, request, response, data, dbSession });

    dbSession.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            Statement stmt = con.createStatement();
            InputStreamReader is = new InputStreamReader(new ByteArrayInputStream(data));
            BufferedReader br = new BufferedReader(is);
            String query;

            try {
                while ((query = br.readLine()) != null) {
                    stmt.executeUpdate(query);
                }
            } catch (IOException e) {
                throw new SQLException(e.getMessage(), e);
            }

            LegacyDAO.close(stmt);
        }
    });

    LanguageDAO.refresh();
    log.debug("importLanguage: void");
}

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

License:Open Source License

/**
 * Import mime types into database/*from  www  .  j ava 2s. co m*/
 */
private void importMimeTypes(String userId, HttpServletRequest request, HttpServletResponse response,
        final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException {
    log.debug("import({}, {}, {}, {}, {})", new Object[] { userId, request, response, data, dbSession });

    dbSession.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            Statement stmt = con.createStatement();
            InputStreamReader is = new InputStreamReader(new ByteArrayInputStream(data));
            BufferedReader br = new BufferedReader(is);
            String query;

            try {
                while ((query = br.readLine()) != null) {
                    stmt.executeUpdate(query);
                }
            } catch (IOException e) {
                throw new SQLException(e.getMessage(), e);
            }

            LegacyDAO.close(stmt);
        }
    });

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

From source file:com.ikon.util.ReportUtils.java

License:Open Source License

/**
 * Execute report//from w w  w  .j av a2  s  . c o m
 */
private static void executeDatabase(Session dbSession, final ByteArrayOutputStream baos, final JasperReport jr,
        final Map<String, Object> params, final int format) {
    dbSession.doWork(new Work() {
        @Override
        public void execute(Connection con) throws SQLException {
            try {
                ReportUtils.generateReport(baos, jr, params, format, con);
            } catch (JRException e) {
                throw new SQLException(e.getMessage(), e);
            }
        }
    });
}

From source file:com.kurento.jpa.CustomHibernateJpaDialect.java

License:Apache License

@Override
public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition)
        throws PersistenceException, SQLException, TransactionException {

    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }//w  w  w  . ja  v a 2s  .  co m

    final TransactionData data = new TransactionData();

    session.doWork(new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(connection,
                    definition);
            data.setPreviousIsolationLevel(previousIsolationLevel);
            data.setConnection(connection);
        }
    });

    entityManager.getTransaction().begin();

    Object springTransactionData = prepareTransaction(entityManager, definition.isReadOnly(),
            definition.getName());

    data.setSpringTransactionData(springTransactionData);

    return data;
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

License:Open Source License

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}./*  w ww. j  av a  2 s  .  c om*/
 * 
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static List<Object[]> runSql(Session session, final String queryString, final Object[] parameters) {
    final List<Object[]> result = new ArrayList<Object[]>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                ResultSet rs = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();
                    while (rs.next()) {
                        Object[] current = new Object[cc];
                        for (int i = 0; i < cc; i++) {
                            current[i] = rs.getObject(i + 1);
                        }
                        result.add(current);
                    }
                } finally {
                    if (null != rs) {
                        rs.close();
                    }
                    if (null != stmt) {
                        stmt.close();
                    }
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

License:Open Source License

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}./*from  w w  w .jav a  2 s  .c  o  m*/
 * 
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
// hongliangpan add
public static List<Map<String, Object>> runSqlReturnMap(Session session, final String queryString,
        final Object[] parameters) {
    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                PreparedStatement stmt = connection.prepareStatement(queryString);
                ResultSet rs = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        stmt.setObject(i + 1, parameters[i]);
                    }
                    rs = stmt.executeQuery();
                    ResultSetMetaData md = rs.getMetaData();
                    int cc = md.getColumnCount();

                    while (rs.next()) {
                        Map<String, Object> t_row = new LinkedHashMap<String, Object>();
                        for (int i = 0; i < cc; i++) {
                            Object t_value = rs.getObject(i + 1);
                            t_row.put(md.getColumnLabel(i + 1), t_value);
                        }
                        result.add(t_row);
                    }
                } finally {
                    if (null != rs) {
                        rs.close();
                    }
                    if (null != stmt) {
                        stmt.close();
                    }
                }
            }
        });
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }

    return result;
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

License:Open Source License

/**
 * Runs a SQL query against a session. The query is processed with an {@link OgnlSqlFormat}, so it can access values
 * from the OGNL context.<br>//w ww.j av a 2  s. co  m
 * INSERT UPDATE DELETE DROP CREATE ALTER TRUNCATE RENAME hongliangpan add
 * 
 * @param session the session
 * @param sql the query string
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static int runSqlDml(Session session, String sql) {
    OgnlSqlFormat sqlFormat = OgnlSqlFormat.create(sql);
    final String queryString = sqlFormat.getFormatString();
    final List<Integer> result = new ArrayList<Integer>();
    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                Statement stmt = connection.createStatement();
                try {
                    result.add(stmt.executeUpdate(queryString));
                } finally {
                    stmt.close();
                }
            }
        });
    } catch (HibernateException e) {
        result.add(-1);
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }
    if (result.size() > 0) {
        return result.get(0);
    }
    return -1;
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

License:Open Source License

/**
 * Runs a SQL query against a session. The query can contain placeholders for the parameters, as supported by
 * {@link PreparedStatement}. <br>
 * INSERT UPDATE DELETE DROP CREATE ALTER TRUNCATE RENAME sueprpan add
 * //w w  w  .  j  a v  a  2  s  . c o m
 * @param session the session
 * @param queryString the query
 * @param parameters parameters to substitute in the query
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static int runSqlDml(Session session, final String queryString, final Object[] parameters) {
    final List<Integer> result = new ArrayList<Integer>();
    try {
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                Statement stmt = connection.createStatement();
                try {
                    result.add(stmt.executeUpdate(queryString));
                } finally {
                    stmt.close();
                }
            }
        });
    } catch (HibernateException e) {
        result.add(-1);
        session.getTransaction().rollback();
        session.beginTransaction();
        throw e;
    }
    if (result.size() > 0) {
        return result.get(0);
    }
    return -1;
}

From source file:com.mimp.hibernate.HiberEtapa.java

public ArrayList<Familia> getListaFamilias() {

    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();/*from   ww  w.  ja  va 2s .  com*/

    final ArrayList<Familia> allFamilias = new ArrayList();

    Work work = new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            ExpedienteNna expnna;

            String hql = "{call HE_FAM_HAB(?)}";
            CallableStatement statement = connection.prepareCall(hql);
            statement.registerOutParameter(1, OracleTypes.CURSOR);
            statement.execute();

            ResultSet rs = (ResultSet) statement.getObject(1);

            while (rs.next()) {
                Set<ExpedienteFamilia> listExp = new HashSet<ExpedienteFamilia>();
                Set<AsistenciaFR> listAFR = new HashSet<AsistenciaFR>();
                Set<FormularioSesion> listFS = new HashSet<FormularioSesion>();

                Familia tempFamp = new Familia();
                tempFamp.setIdfamilia(rs.getLong("IDFAMILIA"));
                tempFamp.setCorreo(rs.getString("CORREO"));
                tempFamp.setHabilitado(rs.getShort("HABILITADO"));
                tempFamp.setConstancia(rs.getString("CONSTANCIA"));

                String hql2 = "{call HE_GET_EXPFAM_BY_IDFAM(?,?)}";
                CallableStatement statement2 = connection.prepareCall(hql2);
                statement2.setLong(1, tempFamp.getIdfamilia());
                statement2.registerOutParameter(2, OracleTypes.CURSOR);
                statement2.execute();

                ResultSet rs2 = (ResultSet) statement2.getObject(2);

                if (rs2.next()) {
                    ExpedienteFamilia tempExpFam = new ExpedienteFamilia();
                    tempExpFam.setIdexpedienteFamilia(rs2.getLong("IDEXPEDIENTE_FAMILIA"));
                    tempExpFam.setExpediente(rs2.getString("EXPEDIENTE"));
                    tempExpFam.setHt(rs2.getString("HT"));

                    listExp.add(tempExpFam);
                }
                rs2.close();
                statement2.close();

                String hql3 = "{call HE_AFR_BY_IDFAM(?,?)}";
                CallableStatement statement3 = connection.prepareCall(hql3);
                statement3.setLong(1, tempFamp.getIdfamilia());
                statement3.registerOutParameter(2, OracleTypes.CURSOR);
                statement3.execute();

                ResultSet rs3 = (ResultSet) statement3.getObject(2);

                while (rs3.next()) {
                    AsistenciaFR tempAFR = new AsistenciaFR();
                    tempAFR.setIdasistenciaFR(rs3.getLong("IDASISTENCIA_F_R"));
                    String asist = "";
                    asist = rs3.getString("ASISTENCIA");
                    if (!rs3.wasNull()) {
                        tempAFR.setAsistencia(asist.charAt(0));
                    }
                    tempAFR.setInasJus(rs3.getShort("INAS_JUS"));
                    tempAFR.setFamilia(tempFamp);

                    listAFR.add(tempAFR);

                }
                rs3.close();
                statement3.close();

                String hql4 = "{call HE_GET_FS_BY_IDFAM(?,?)}";
                CallableStatement statement4 = connection.prepareCall(hql4);
                statement4.setLong(1, tempFamp.getIdfamilia());
                statement4.registerOutParameter(2, OracleTypes.CURSOR);
                statement4.execute();

                ResultSet rs4 = (ResultSet) statement4.getObject(2);

                if (rs4.next()) {
                    FormularioSesion tempFS = new FormularioSesion();
                    Sesion tempSesion = new Sesion();
                    tempFS.setIdformularioSesion(rs4.getLong("IDFORMULARIO_SESION"));
                    tempSesion.setIdsesion(rs4.getLong("IDSESION"));
                    tempSesion.setUnidad(rs4.getString("UNIDAD"));
                    Set<Asistente> listA = new HashSet<Asistente>();

                    String hql5 = "{call HE_GET_ASIS_BY_IDFS(?,?)}";
                    CallableStatement statement5 = connection.prepareCall(hql5);
                    statement5.setLong(1, tempFS.getIdformularioSesion());
                    statement5.registerOutParameter(2, OracleTypes.CURSOR);
                    statement5.execute();
                    ResultSet rs5 = (ResultSet) statement5.getObject(2);

                    while (rs5.next()) {
                        Asistente tempAsis = new Asistente();
                        tempAsis.setIdasistente(rs5.getLong("IDASISTENTE"));
                        tempAsis.setNombre(rs5.getString("NOMBRE"));
                        tempAsis.setApellidoP(rs5.getString("APELLIDO_P"));
                        tempAsis.setApellidoM(rs5.getString("APELLIDO_M"));
                        String tempsexo = "";
                        tempsexo = rs5.getString("SEXO");
                        if (!rs5.wasNull()) {
                            tempAsis.setSexo(tempsexo.charAt(0));
                        }
                        tempAsis.setEdad(rs5.getShort("EDAD"));
                        tempAsis.setCorreo(rs5.getString("CORREO"));
                        tempAsis.setFormularioSesion(tempFS);

                        listA.add(tempAsis);
                    }
                    rs5.close();
                    statement5.close();

                    tempFS.setSesion(tempSesion);
                    tempFS.setAsistentes(listA);
                    listFS.add(tempFS);
                }
                rs4.close();
                statement4.close();

                tempFamp.setExpedienteFamilias(listExp);
                tempFamp.setAsistenciaFRs(listAFR);
                tempFamp.setFormularioSesions(listFS);

                allFamilias.add(tempFamp);
            }
            rs.close();
            statement.close();
        }
    };

    session.doWork(work);

    return allFamilias;

}

From source file:com.mimp.hibernate.HiberEtapa.java

public Familia getFamilia(final long id) {
    Session session = sessionFactory.getCurrentSession();

    final Familia fam = new Familia();
    final Entidad ent = new Entidad();

    Work work = new Work() {
        @Override//  w w  w  .  jav  a2s.c o m
        public void execute(Connection connection) throws SQLException {

            String hql = "{call HE_GETFAMILIA(?, ?)}";
            CallableStatement statement = connection.prepareCall(hql);
            statement.setLong(1, id);
            statement.registerOutParameter(2, OracleTypes.CURSOR);
            statement.execute();

            temp = (ResultSet) statement.getObject(2);
            while (temp.next()) {
                fam.setIdfamilia(temp.getShort(1));
                if (temp.getShort(2) != 0) {

                    String hql2 = "{call HE_GETENTIDAD(?, ?)}";
                    CallableStatement statement2 = connection.prepareCall(hql2);
                    statement2.setLong(1, temp.getShort(2));
                    statement2.registerOutParameter(2, OracleTypes.CURSOR);
                    statement2.execute();
                    temp2 = (ResultSet) statement2.getObject(2);
                    while (temp2.next()) {
                        ent.setIdentidad(temp2.getShort(1));
                        ent.setNombre(temp2.getString(2));
                        ent.setUser(temp2.getString(3));
                        ent.setPass(temp2.getString(4));
                        ent.setDireccion(temp2.getString(5));
                        ent.setTelefono(temp2.getString(6));
                        ent.setPais(temp2.getString(7));
                        ent.setResolAuto(temp2.getString(8));
                        ent.setFechaResol(temp2.getDate(9));
                        ent.setResolRenov(temp2.getString(10));
                        ent.setFechaRenov(temp2.getDate(11));
                        ent.setFechaVenc(temp2.getDate(12));
                        ent.setObs(temp2.getString(13));
                        ent.setCorreo(temp2.getString(14));
                        fam.setEntidad(ent);
                    }
                    temp2.close();
                    statement2.close();
                }
                fam.setUser(temp.getString(3));
                fam.setPass(temp.getString(4));
                fam.setCorreo(temp.getString(5));
                fam.setHabilitado(temp.getShort(6));
                fam.setConstancia(temp.getString(7));

            }
            temp.close();
            statement.close();
        }
    };
    session.doWork(work);

    return fam;
}