List of usage examples for org.hibernate Session getSessionFactory
SessionFactory getSessionFactory();
From source file:com.autobizlogic.abl.hibernate.HibernateUtil.java
License:Open Source License
/** * Given two persistent beans, which may or may not be proxies, determine whether they refer * to the same persistent object. In other words, are they of the same class, and do they * have the same primary key?//from www .j a v a 2 s.c o m * If both beans are null, this will return true. */ public static boolean beansHaveSamePK(Object bean1, Object bean2, Session session) { if (bean1 == null && bean2 == null) return true; if (bean1 == null && bean2 != null) return false; if (bean1 != null && bean2 == null) return false; if (bean1 == bean2) return true; String bean1ClassName = getEntityNameForObject(bean1); String bean2ClassName = getEntityNameForObject(bean2); if (!bean1ClassName.equals(bean2ClassName)) return false; SessionFactory sf = session.getSessionFactory(); ClassMetadata meta = sf.getClassMetadata(bean1ClassName); if (meta == null) throw new RuntimeException("Unable to get Hibernate metadata for: " + bean1ClassName); Object pk1 = meta.getIdentifier(bean1, (SessionImplementor) session); Object pk2 = meta.getIdentifier(bean2, (SessionImplementor) session); if (pk1 == null || pk2 == null) return false; return pk1.equals(pk2); }
From source file:com.axelor.report.ReportGenerator.java
License:Open Source License
@SuppressWarnings("unchecked") public void generate(OutputStream output, String designName, String format, Map<String, Object> params, Locale locale) throws IOException, BirtException { final IResourceLocator locator = engine.getConfig().getResourceLocator(); final URL found = locator.findResource(null, designName, IResourceLocator.OTHERS); if (found == null) { throw new BirtException("No such report found: " + designName); }//w w w . ja va 2 s. co m final InputStream stream = found.openStream(); try { final IReportRunnable report = engine.openReportDesign(designName, stream); final IRunAndRenderTask task = engine.createRunAndRenderTask(report); final IRenderOption opts = new RenderOption(); opts.setOutputFormat(format); opts.setOutputStream(output); task.setLocale(locale); task.setRenderOption(opts); task.setParameterValues(params); Session session = JPA.em().unwrap(Session.class); SessionFactoryImpl sessionFactory = (SessionFactoryImpl) session.getSessionFactory(); Connection connection = null; try { connection = sessionFactory.getConnectionProvider().getConnection(); } catch (SQLException e) { throw Throwables.propagate(e); } task.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, getClass().getClassLoader()); task.getAppContext().put(IConnectionFactory.PASS_IN_CONNECTION, connection); task.getAppContext().put(IConnectionFactory.CLOSE_PASS_IN_CONNECTION, Boolean.FALSE); try { task.run(); } finally { task.close(); } } finally { stream.close(); } }
From source file:com.biosis.biosislite.dao.DAOBiosis.java
@Override public Connection getConexion() { Session sesion = (Session) getEntityManager().getDelegate(); SessionFactoryImpl sessionFactory = (SessionFactoryImpl) sesion.getSessionFactory(); Connection connection = null; try {/*from w w w .j a v a 2 s. co m*/ connection = sessionFactory.getConnectionProvider().getConnection(); if (connection == null) { LOG.error("NO SE PUDO OBTENER LA CONEXION"); } } catch (SQLException e) { LOG.error("ERROR " + e.getMessage()); em = null; } return connection; }
From source file:com.blazebit.persistence.impl.hibernate.function.HibernateEntityManagerIntegrator.java
License:Apache License
private Dialect getDialect(EntityManager em) { Session s = em.unwrap(Session.class); SessionFactoryImplementor sf = (SessionFactoryImplementor) s.getSessionFactory(); return sf.getDialect(); }
From source file:com.blazebit.persistence.integration.hibernate.base.function.AbstractHibernateEntityManagerFactoryIntegrator.java
License:Apache License
@Override public Map<String, JpqlFunction> getRegisteredFunctions(EntityManagerFactory entityManagerFactory) { EntityManager em = null;/*from ww w. ja v a 2 s . c o m*/ try { em = entityManagerFactory.createEntityManager(); Session s = em.unwrap(Session.class); SessionFactoryImplementor sf = (SessionFactoryImplementor) s.getSessionFactory(); Map<String, SQLFunction> functions = getFunctions(s); Map<String, JpqlFunction> map = new HashMap<>(functions.size()); for (Map.Entry<String, SQLFunction> entry : functions.entrySet()) { SQLFunction function = entry.getValue(); if (function instanceof HibernateJpqlFunctionAdapter) { map.put(entry.getKey(), ((HibernateJpqlFunctionAdapter) function).unwrap()); } else { map.put(entry.getKey(), new HibernateSQLFunctionAdapter(sf, entry.getValue())); } } return map; } finally { if (em != null) { em.close(); } } }
From source file:com.blazebit.persistence.integration.hibernate.base.function.AbstractHibernateEntityManagerFactoryIntegrator.java
License:Apache License
@SuppressWarnings("unchecked") private Map<String, SQLFunction> getFunctions(Session s) { if (MAJOR < 5 || (MAJOR == 5 && MINOR == 0 && FIX == 0 && "Beta1".equals(TYPE))) { // Implementation detail: Hibernate uses a mutable map, so we can do this return getDialect(s).getFunctions(); } else {//from w w w .j a v a2 s . c o m SessionFactoryImplementor sf = (SessionFactoryImplementor) s.getSessionFactory(); SQLFunctionRegistry registry = sf.getSqlFunctionRegistry(); Exception ex; // We have to retrieve the functionMap the old fashioned way via reflection :( Field f = null; boolean madeAccessible = false; try { f = SQLFunctionRegistry.class.getDeclaredField("functionMap"); madeAccessible = !f.isAccessible(); if (madeAccessible) { f.setAccessible(true); } return (Map<String, SQLFunction>) f.get(registry); } catch (NoSuchFieldException e) { ex = e; } catch (IllegalArgumentException e) { // This can never happen ex = e; } catch (IllegalAccessException e) { ex = e; } finally { if (f != null && madeAccessible) { f.setAccessible(false); } } throw new RuntimeException( "Could not access the function map to dynamically register functions. Please report this version of hibernate(" + VERSION_STRING + ") so we can provide support for it!", ex); } }
From source file:com.blazebit.persistence.integration.hibernate.base.function.AbstractHibernateEntityManagerFactoryIntegrator.java
License:Apache License
private void replaceFunctions(Session s, Map<String, SQLFunction> newFunctions) { if (MAJOR < 5 || (MAJOR == 5 && MINOR == 0 && FIX == 0 && "Beta1".equals(TYPE))) { Exception ex;/*w w w.j a v a2 s . c o m*/ Field f = null; boolean madeAccessible = false; try { f = Dialect.class.getDeclaredField("sqlFunctions"); madeAccessible = !f.isAccessible(); if (madeAccessible) { f.setAccessible(true); } f.set(getDialect(s), newFunctions); return; } catch (NoSuchFieldException e) { ex = e; } catch (IllegalArgumentException e) { // This can never happen ex = e; } catch (IllegalAccessException e) { ex = e; } finally { if (f != null && madeAccessible) { f.setAccessible(false); } } throw new RuntimeException( "Could not access the function map to dynamically register functions. Please report this version of hibernate(" + VERSION_STRING + ") so we can provide support for it!", ex); } else { SessionFactoryImplementor sf = (SessionFactoryImplementor) s.getSessionFactory(); SQLFunctionRegistry registry = sf.getSqlFunctionRegistry(); Exception ex; // We have to retrieve the functionMap the old fashioned way via reflection :( Field f = null; boolean madeAccessible = false; try { f = SQLFunctionRegistry.class.getDeclaredField("functionMap"); madeAccessible = !f.isAccessible(); if (madeAccessible) { f.setAccessible(true); } f.set(registry, newFunctions); return; } catch (NoSuchFieldException e) { ex = e; } catch (IllegalArgumentException e) { // This can never happen ex = e; } catch (IllegalAccessException e) { ex = e; } finally { if (f != null && madeAccessible) { f.setAccessible(false); } } throw new RuntimeException( "Could not access the function map to dynamically register functions. Please report this version of hibernate(" + VERSION_STRING + ") so we can provide support for it!", ex); } }
From source file:com.blazebit.persistence.integration.hibernate.base.function.AbstractHibernateEntityManagerFactoryIntegrator.java
License:Apache License
protected Dialect getDialect(Session s) { SessionFactoryImplementor sf = (SessionFactoryImplementor) s.getSessionFactory(); return sf.getDialect(); }
From source file:com.cms.dao.TermInformationDAO.java
License:Open Source License
public ResultDTO insertBatchTermInformations(List<TermInformationDTO> lstTermInformationDTO) { ResultDTO resultDTO = new ResultDTO(); try {//from w ww. j ava 2 s. c o m Session sessionBatch = sessionFactory.openSession(); Connection connection; SessionFactory sessionFactoryBatch = sessionBatch.getSessionFactory(); connection = sessionFactoryBatch.getSessionFactoryOptions().getServiceRegistry() .getService(ConnectionProvider.class).getConnection(); StringBuilder sql = new StringBuilder(); List params; sql.append(" INSERT INTO TERM_INFORMATION(ID,EMAIL,END_TIME,MINE_NAME," + "PHONE,PROVIDER,SERVICE,START_TIME,TAX_CODE,SOURCE_DATA, IS_CONTACT_INFO) " + "values(TERM_INFORMATION_SEQ.nextval, ?, to_date(?,'dd/MM/yyyy'), ?, ?, ?, ?, to_date(?,'dd/MM/yyyy') , ?, ?, ?) " + " LOG ERRORS REJECT LIMIT UNLIMITED "); //tao statement bang preparestatement PreparedStatement stm = connection.prepareStatement(sql.toString()); int numberNeedToCommit = 0; int numberOfSuccess = 0; int numberOfFail = 0; for (TermInformationDTO t : lstTermInformationDTO) { params = getParamsFromTermInfo(t); for (int idx = 0; idx < params.size(); idx++) { try { stm.setString(idx + 1, DataUtil.nvl(params.get(idx), "").toString()); } catch (Exception e) { System.out.println(idx); } } stm.addBatch(); numberNeedToCommit++; if (numberNeedToCommit >= 1000) { try { stm.executeBatch(); numberOfSuccess = numberOfSuccess + numberNeedToCommit; } catch (Exception ex) { numberOfFail = numberOfFail + numberNeedToCommit; } numberNeedToCommit = 0; } } if (numberNeedToCommit > 0) { try { stm.executeBatch(); numberOfSuccess += numberNeedToCommit; } catch (Exception ex) { numberOfFail += numberNeedToCommit; } } stm.close(); sessionBatch.close(); numberOfFail = getNumberOfErrorRecord(connection); connection.close(); numberOfSuccess -= numberOfFail; resultDTO.setKey(Constants.SUCCESS); resultDTO.setMessage(Constants.SUCCESS); resultDTO.setQuantityFail(numberOfFail); resultDTO.setQuantitySucc(numberOfSuccess); } catch (SQLException ex) { resultDTO.setKey(Constants.FAIL); resultDTO.setMessage(Constants.FAIL); Logger.getLogger(TermInformationDAO.class.getName()).log(Level.SEVERE, null, ex); } return resultDTO; }
From source file:com.conecta.sat.controller.CentroFinancieroVirtualController.java
@RequestMapping(value = "virtualCenterReportPDF.do", method = RequestMethod.GET) public String virtualCenterReportPDF(HttpServletRequest request, HttpServletResponse resp) throws JRException, SQLException, IOException, Exception { String url = request.getSession().getServletContext() .getRealPath("/resources/reports/CentroFinancieroVirtual.jasper"); logger.info("URL: " + url); Map parameters = new HashMap(); StockTokenadmin soft = new StockTokenadmin(); soft = this.stockTokenAdminServiceImpl.getStockSoft(); parameters.put("stockUtilizado", soft.getStockUtilizado()); parameters.put("stockTotal", soft.getStockTotal()); try {/*w w w . j a v a 2 s. c om*/ Session session = em.unwrap(Session.class); SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory(); ConnectionProvider cp = sfi.getConnectionProvider(); Connection conn = cp.getConnection(); JasperPrint jasperPrint = JasperFillManager.fillReport(url, parameters, conn); byte[] pdfBytes = JasperExportManager.exportReportToPdf(jasperPrint); DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss"); //uncomment this line to make browser download the file resp.setContentType("application/pdf"); resp.setHeader("Content-Disposition", "attachment;filename=CentroFinancieroVirtual" + name.format(new Date()) + ".pdf"); resp.getOutputStream().write(pdfBytes); resp.getOutputStream().flush(); resp.getOutputStream().close(); resp.flushBuffer(); } catch (JRException ex) { logger.error(ex.getMessage(), ex.getCause()); } catch (IOException ex) { logger.error(ex.getMessage(), ex.getCause()); } return null; }