List of usage examples for org.hibernate Session doWork
void doWork(Work work) throws HibernateException;
From source file:org.zht.framework.zhtdao.hibernate.impl.HibernateBaseDaoImpl.java
License:Apache License
@Override public void executeUpdateSqlStatement(final String sql, final Object[] parameters) throws DaoException { Session session = this.getCurrentSession(); session.doWork(new Work() { public void execute(Connection conn) throws SQLException { try { PreparedStatement ps = conn.prepareStatement(sql); int i = 0; if (parameters != null && parameters.length > 0) { for (Object str : parameters) { i++;/*from w ww . j av a2 s .c o m*/ ps.setString(i, (String) str); } } ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:pl.com.bottega.testutils.HibernateExtendedJpaDialect.java
License:Apache License
/** * This method is overridden to set custom isolation levels on the connection * @param entityManager/*from w w w . j av a2 s .c o m*/ * @param definition * @return * @throws PersistenceException * @throws SQLException * @throws TransactionException */ @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()); } entityManager.getTransaction().begin(); logger.debug("Transaction started"); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { logger.debug("The connection instance is {}", connection); logger.debug( "The isolation level of the connection is {} and the isolation level set on the transaction is {}", connection.getTransactionIsolation(), definition.getIsolationLevel()); DataSourceUtils.prepareConnectionForTransaction(connection, definition); } }); return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); }
From source file:poo.mercado.controller.GestorReporte.java
/** * Generamos un reporte en pantalla usando la librera de JasperReports, * recibimos como entrada los valores ingresados en pantalla y compilamos * el reporte en formato XML para mostrarlo con el componente visual * JasperViewer.//from w w w. j a va2 s.c o m * * @param tiposPuesto * @param estados */ public void generarReporte(List<TipoPuesto> tiposPuesto, List<Estado> estados) { System.out.println("Tipos: " + tiposPuesto); System.out.println("Estados: " + estados); // abrimos una sesion de hibernate Session session = sessionFactory.openSession(); // creamos las listas de IDs para incluir en la consulta SQL del reporte List<Integer> idsTiposPuesto = obtenerListaDeIdsTiposPuesto(tiposPuesto); List<Integer> idsEstados = obtenerListaDeIdsEstados(estados); // utilizamos la sesion de hibernate para acceder a la conexion JDBC session.doWork(new Work() { @Override public void execute(Connection conexion) throws SQLException { try { // armamos el modelo de parametros Map<String, Object> parametros = new HashMap<>(); parametros.put("idsTiposPuesto", idsTiposPuesto); parametros.put("idsEstados", idsEstados); // creamos el reporte InputStream design = getClass() .getResourceAsStream("/resources/reportes/puestos-por-estado.jrxml"); JasperDesign jasperDesing = JRXmlLoader.load(design); JasperReport reporte = JasperCompileManager.compileReport(jasperDesing); // imprimimos el reporte con los parametros JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, conexion); // visualizamos el reporte en pantalla JasperViewer.viewReport(jasperPrint, false); } catch (JRException ex) { System.out.println("Error al generar el reporte: " + ex.getMessage()); } } }); // cerramos la sesion session.close(); }
From source file:poo.pizzeria.controller.GestorReporte.java
/** * Generamos un reporte en pantalla usando la librera de JasperReports, * recibimos como entrada los valores ingresados en pantalla y compilamos * el reporte en formato XML para mostrarlo con el componente visual * JasperViewer./*from w ww . j ava2 s . c o m*/ * * @param txtFechaDesde * @param txtFechaHasta */ public void generarReporte(String txtFechaDesde, String txtFechaHasta) { // inicializamos el formato de las fechas SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // intentamos generar las fechas try { Date fechaDesde = sdf.parse(txtFechaDesde); Date fechaHasta = sdf.parse(txtFechaHasta); // si la fecha desde no es anterior a hasta if (!fechaDesde.before(fechaHasta)) { JOptionPane.showMessageDialog(pantalla, "La fecha hasta debe ser posterior a desde", "Fechas incorrectas", JOptionPane.ERROR_MESSAGE); } else // si la fecha hasta no es anterior a hoy if (!fechaHasta.before(new Date())) { JOptionPane.showMessageDialog(pantalla, "La fecha hasta debe ser anterior a hoy", "Fechas incorrectas", JOptionPane.ERROR_MESSAGE); } else { // abrimos una sesion de hibernate Session session = sessionFactory.openSession(); // utilizamos la sesion de hibernate para acceder a la conexion JDBC session.doWork(new Work() { @Override public void execute(Connection conexion) throws SQLException { try { // armamos el modelo de parametros Map<String, Object> parametros = new HashMap<>(); parametros.put("fechaDesde", fechaDesde); parametros.put("fechaHasta", fechaHasta); // creamos el reporte InputStream design = getClass() .getResourceAsStream("/resources/reportes/variedades-mas-vendidas.jrxml"); JasperDesign jasperDesing = JRXmlLoader.load(design); JasperReport reporte = JasperCompileManager.compileReport(jasperDesing); // imprimimos el reporte con los parametros JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, conexion); // visualizamos el reporte en pantalla JasperViewer.viewReport(jasperPrint, false); } catch (JRException ex) { System.out.println("Error al generar el reporte: " + ex.getMessage()); } } }); // cerramos la sesion session.close(); } } catch (ParseException ex) { JOptionPane.showMessageDialog(pantalla, "El formato de fechas debe ser dd/mm/aaaa", "Formato de fechas incorrecto", JOptionPane.ERROR_MESSAGE); } }
From source file:relatorio.relatorioDeCidades.java
public void emitir() { Map<String, Object> parametros = new HashMap<>(); // parametros.put("data_inicio", this.getDataInicio()); // parametros.put("data_fim", this.getDataFim()); ExecutorRelatorio relatorio = new ExecutorRelatorio("/relatorios/relatorio_cidades.jasper", this.response, parametros, "Relatorio de cidades.pdf"); // ExecutorRelatorio relatorio = new ExecutorRelatorio("/relatorios/relatorio_cidades.jasper", // null, null, "Relatorio de cidades.pdf"); Session session = manager.unwrap(Session.class); session.doWork(relatorio); facesContext.responseComplete();/*w w w . j a va 2 s. com*/ }
From source file:solidstack.query.hibernate.HibernateSupport.java
License:Apache License
/** * Retrieves a {@link ResultSet} from the given Hibernate {@link Session}. * * @param query The query.//from w w w .j a v a 2 s . co m * @param session The Hibernate {@link Session} to use. * @param args The arguments to the query. When a map, then the contents of the map. When an Object, then the JavaBean properties. * @return a {@link ResultSet}. * @throws JDBCException SQLExceptions are translated to JDBCExceptions by Hibernate. * @see Query#resultSet(Connection, Object) */ static public ResultSet resultSet(final Query query, Session session, final Object args) { final ResultHolder<ResultSet> result = new ResultHolder<ResultSet>(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { try { result.set(query.resultSet(connection, args)); } catch (QuerySQLException e) { throw e.getSQLException(); } } }); return result.get(); }
From source file:solidstack.query.hibernate.HibernateSupport.java
License:Apache License
/** * Retrieves a {@link List} of {@link Object} arrays from the given Hibernate {@link Session}. * * @param query The query.//from www . j a v a 2s. co m * @param session The Hibernate {@link Session} to use. * @param args The arguments to the query. When a map, then the contents of the map. When an Object, then the JavaBean properties. * @return a {@link List} of {@link Object} arrays. * @throws JDBCException SQLExceptions are translated to JDBCExceptions by Hibernate. * @see Query#listOfArrays(Connection, Object) */ static public List<Object[]> listOfArrays(final Query query, final Session session, final Object args) { final ResultHolder<List<Object[]>> result = new ResultHolder<List<Object[]>>(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { try { result.set(query.listOfArrays(connection, args)); } catch (QuerySQLException e) { throw e.getSQLException(); } } }); return result.get(); }
From source file:solidstack.query.hibernate.HibernateSupport.java
License:Apache License
/** * Retrieves a {@link List} of {@link Map}s from the given Hibernate {@link Session}. * * @param query The query.//from w ww. j a va 2 s .com * @param session The Hibernate {@link Session} to use. * @param args The arguments to the query. When a map, then the contents of the map. When an Object, then the JavaBean properties. * @return A {@link List} of {@link Map}s. * @throws JDBCException SQLExceptions are translated to JDBCExceptions by Hibernate. * @see Query#listOfMaps(Connection, Object) */ static public List<Map<String, Object>> listOfMaps(final Query query, final Session session, final Object args) { final ResultHolder<List<Map<String, Object>>> result = new ResultHolder<List<Map<String, Object>>>(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { try { result.set(query.listOfMaps(connection, args)); } catch (QuerySQLException e) { throw e.getSQLException(); } } }); return result.get(); }
From source file:solidstack.query.hibernate.HibernateSupport.java
License:Apache License
/** * Executes an update (DML) or a DDL query through the given Hibernate {@link Session}. * * @param query The query.//w ww. j a va2s. com * @param session The Hibernate {@link Session} to use. * @param args The arguments to the query. When a map, then the contents of the map. When an Object, then the JavaBean properties. * @return The row count from a DML statement or 0 for SQL that does not return anything. * @throws JDBCException SQLExceptions are translated to JDBCExceptions by Hibernate. * @see Query#updateChecked(Connection, Object) */ static public int update(final Query query, Session session, final Object args) { final ResultHolder<Integer> result = new ResultHolder<Integer>(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { result.set(query.updateChecked(connection, args)); } }); return result.get(); }
From source file:space.npstr.wolfia.db.ColumnMapper.java
License:Open Source License
public static Map<String, Integer> getColumnNameToIndexMap(final String queryString, final EntityManager em) throws SQLException { final Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific! final AtomicReference<ResultSetMetaData> msRef = new AtomicReference<>(); session.doWork((c) -> { try (final PreparedStatement statement = create(c, queryString)) { // I'm not setting parameters here, because I just want to find out about the return values' column names msRef.set(statement.getMetaData()); }// ww w.j a v a2 s . c o m }); final ResultSetMetaData metaData = msRef.get(); // LinkedHashmap preserves order of insertion: final Map<String, Integer> columnNameToColumnIndex = new LinkedHashMap<>(); for (int t = 0; t < metaData.getColumnCount(); ++t) { // important, first index in the metadata is "1", the first index for the result array must be "0" columnNameToColumnIndex.put(metaData.getColumnName(t + 1), t); } return columnNameToColumnIndex; }