List of usage examples for org.hibernate.cfg Configuration getProperty
public String getProperty(String propertyName)
From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java
License:Open Source License
private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName) throws HibernateException { //ClassLoader cl1; if (sessionFactory == null) { if (jndiName == null || jndiName.trim().length() == 0) jndiName = CommonConstant.DEFAULT_JNDI_URL; Context initCtx = null;/* w w w . j a v a 2 s . c o m*/ try { initCtx = new InitialContext(); sessionFactory = (SessionFactory) initCtx.lookup(jndiName); return; } catch (Exception e) { logger.log(Level.INFO, "Unable to get JNDI data source connection", e); } finally { if (initCtx != null) try { initCtx.close(); } catch (NamingException e) { //ignore } } Thread thread = Thread.currentThread(); try { //Class.forName("org.hibernate.Configuration"); //Configuration ffff = new Configuration(); //Class.forName("org.apache.commons.logging.LogFactory"); oldloader = thread.getContextClassLoader(); //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration"); //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory"); //refreshURLs(); //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader()); ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader); //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0])); thread.setContextClassLoader(testLoader); //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration"); //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader); //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader); //Configuration cfg=null; //cfg = new Configuration(); //Object oo = cls.newInstance(); //Configuration cfg = (Configuration)oo; Configuration cfg = new Configuration(); buildConfig(hibfile, mapdir, cfg); Class<? extends Driver> driverClass = testLoader .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class); Driver driver = driverClass.newInstance(); WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class")); boolean foundDriver = false; Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver nextDriver = (Driver) drivers.nextElement(); if (nextDriver.getClass() == wd.getClass()) { if (nextDriver.toString().equals(wd.toString())) { foundDriver = true; break; } } } if (!foundDriver) { DriverManager.registerDriver(wd); } sessionFactory = cfg.buildSessionFactory(); //configuration = cfg; HibernateMapDirectory = mapdir; HibernateConfigFile = hibfile; } catch (Throwable e) { e.printStackTrace(); throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e); } finally { thread.setContextClassLoader(oldloader); } } }
From source file:com.minhafazenda.model.MfAuditoriaConfiguracaoModel.java
public void criaProcedureViewAuditoria(String nomeTabela) { Configuration configuration = new Configuration(); configuration.configure();//from w ww . ja v a 2 s.com String DBURL = configuration.getProperty("hibernate.connection.url"); String DBDRIVER = configuration.getProperty("hibernate.connection.driver_class"); String usuario = configuration.getProperty("hibernate.connection.username"); String senha = configuration.getProperty("hibernate.connection.password"); String database = configuration.getProperty("hibernate.connection.database"); DBURL += "&user=" + usuario + "&password=" + senha; Statement stmt = null; try { try { Class.forName(DBDRIVER).newInstance(); Connection connection = DriverManager.getConnection(DBURL); stmt = connection.createStatement(); } catch (InstantiationException | IllegalAccessException | SQLException ex) { Logger.getLogger(MfAuditoriaConfiguracaoModel.class.getName()).log(Level.SEVERE, null, ex); } } catch (ClassNotFoundException ex) { Logger.getLogger(MfAuditoriaConfiguracaoModel.class.getName()).log(Level.SEVERE, null, ex); } Session objSession = this.objSessionFactory.openSession(); Query query = objSession .createSQLQuery("CALL mf_auditoria_gerar_script(:nome_banco, :nome_tabela, @errors)") .setParameter("nome_banco", database).setParameter("nome_tabela", nomeTabela); for (Object obj : query.list()) { try { stmt.execute(obj.toString()); } catch (SQLException ex) { Logger.getLogger(MfAuditoriaConfiguracaoModel.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.mpaike.core.database.hibernate.DialectFactoryBean.java
License:Open Source License
/** * Substitute the dialect with an alternative, if possible. * //from w ww . j a va2 s.c o m * @param cfg * the configuration * @param dialect * the dialect * @return the dialect */ private Dialect changeDialect(Configuration cfg, Dialect dialect) { String dialectName = cfg.getProperty(Environment.DIALECT); if (dialectName == null || dialectName.length() == 0) { // Fix the dialect property to match the detected dialect cfg.setProperty(Environment.DIALECT, dialect.getClass().getName()); } return dialect; // TODO: https://issues.42y.net/jira/browse/ETHREEOH-679 // else if (dialectName.equals(Oracle9Dialect.class.getName())) // { // String subst = WWFOracle9Dialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } // else if (dialectName.equals(MySQLDialect.class.getName())) // { // String subst = MySQLInnoDBDialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } // else if (dialectName.equals(MySQL5Dialect.class.getName())) // { // String subst = MySQLInnoDBDialect.class.getName(); // LogUtil.warn(logger, WARN_DIALECT_SUBSTITUTING, dialectName, subst); // cfg.setProperty(Environment.DIALECT, subst); // } }
From source file:com.netspective.tool.hibernate.document.diagram.HibernateDiagramGenerator.java
License:Open Source License
public HibernateDiagramGenerator(final Configuration configuration, final GraphvizDiagramGenerator graphvizDiagramGenerator, final HibernateDiagramGeneratorFilter schemaDiagramFilter) throws HibernateDiagramGeneratorException { this.configuration = configuration; this.graphvizDiagramGenerator = graphvizDiagramGenerator; this.diagramFilter = schemaDiagramFilter; // the following was copied from org.hibernate.cfg.Configuration.buildMapping() because buildMapping() was private this.mapping = new Mapping() { /**//ww w .java 2 s . c om * Returns the identifier type of a mapped class */ public Type getIdentifierType(String persistentClass) throws MappingException { final PersistentClass pc = configuration.getClassMapping(persistentClass); if (pc == null) throw new MappingException("persistent class not known: " + persistentClass); return pc.getIdentifier().getType(); } public String getIdentifierPropertyName(String persistentClass) throws MappingException { final PersistentClass pc = configuration.getClassMapping(persistentClass); if (pc == null) throw new MappingException("persistent class not known: " + persistentClass); if (!pc.hasIdentifierProperty()) return null; return pc.getIdentifierProperty().getName(); } public Type getPropertyType(String persistentClass, String propertyName) throws MappingException { final PersistentClass pc = configuration.getClassMapping(persistentClass); if (pc == null) throw new MappingException("persistent class not known: " + persistentClass); Property prop = pc.getProperty(propertyName); if (prop == null) throw new MappingException("property not known: " + persistentClass + '.' + propertyName); return prop.getType(); } }; String dialectName = configuration.getProperty(Environment.DIALECT); if (dialectName == null) dialectName = org.hibernate.dialect.GenericDialect.class.getName(); try { final Class cls = Class.forName(dialectName); this.dialect = (Dialect) cls.newInstance(); } catch (Exception e) { throw new HibernateDiagramGeneratorException(e); } for (final Iterator classes = configuration.getClassMappings(); classes.hasNext();) { final PersistentClass pclass = (PersistentClass) classes.next(); final Table table = (Table) pclass.getTable(); tableToClassMap.put(table, pclass); } }
From source file:com.openkm.dao.HibernateUtil.java
License:Open Source License
/** * Get instance/*from w w w .jav a2 s . co m*/ */ public static SessionFactory getSessionFactory(String hbm2ddl) { if (sessionFactory == null) { try { // Configure Hibernate Configuration cfg = getConfiguration().configure(); cfg.setProperty("hibernate.dialect", Config.HIBERNATE_DIALECT); cfg.setProperty("hibernate.connection.datasource", Config.HIBERNATE_DATASOURCE); cfg.setProperty("hibernate.hbm2ddl.auto", hbm2ddl); cfg.setProperty("hibernate.show_sql", Config.HIBERNATE_SHOW_SQL); cfg.setProperty("hibernate.generate_statistics", Config.HIBERNATE_STATISTICS); cfg.setProperty("hibernate.search.analyzer", Config.HIBERNATE_SEARCH_ANALYZER); cfg.setProperty("hibernate.search.default.directory_provider", "org.hibernate.search.store.FSDirectoryProvider"); cfg.setProperty("hibernate.search.default.indexBase", Config.HIBERNATE_SEARCH_INDEX_HOME); cfg.setProperty("hibernate.search.default.exclusive_index_use", Config.HIBERNATE_SEARCH_INDEX_EXCLUSIVE); cfg.setProperty("hibernate.search.default.optimizer.operation_limit.max", "500"); cfg.setProperty("hibernate.search.default.optimizer.transaction_limit.max", "75"); cfg.setProperty("hibernate.worker.execution", "async"); // http://relation.to/Bloggers/PostgreSQLAndBLOBs // cfg.setProperty("hibernate.jdbc.use_streams_for_binary", "false"); // Show configuration log.info("Hibernate 'hibernate.dialect' = {}", cfg.getProperty("hibernate.dialect")); log.info("Hibernate 'hibernate.connection.datasource' = {}", cfg.getProperty("hibernate.connection.datasource")); log.info("Hibernate 'hibernate.hbm2ddl.auto' = {}", cfg.getProperty("hibernate.hbm2ddl.auto")); log.info("Hibernate 'hibernate.show_sql' = {}", cfg.getProperty("hibernate.show_sql")); log.info("Hibernate 'hibernate.generate_statistics' = {}", cfg.getProperty("hibernate.generate_statistics")); log.info("Hibernate 'hibernate.search.default.directory_provider' = {}", cfg.getProperty("hibernate.search.default.directory_provider")); log.info("Hibernate 'hibernate.search.default.indexBase' = {}", cfg.getProperty("hibernate.search.default.indexBase")); if (HBM2DDL_CREATE.equals(hbm2ddl)) { // In case of database schema creation, also clean filesystem data. // This means, conversion cache, file datastore and Lucene indexes. log.info("Cleaning filesystem data from: {}", Config.REPOSITORY_HOME); FileUtils.deleteQuietly(new File(Config.REPOSITORY_HOME)); } // Create database schema, if needed sessionFactory = cfg.buildSessionFactory(); if (HBM2DDL_CREATE.equals(hbm2ddl)) { log.info("Executing specific import for: {}", Config.HIBERNATE_DIALECT); InputStream is = ConfigUtils.getResourceAsStream("default.sql"); String adapted = DatabaseDialectAdapter.dialectAdapter(is, Config.HIBERNATE_DIALECT); executeSentences(new StringReader(adapted)); IOUtils.closeQuietly(is); } if (HBM2DDL_CREATE.equals(hbm2ddl) || HBM2DDL_UPDATE.equals(hbm2ddl)) { // Create or update translations for (String res : ConfigUtils.getResources("i18n")) { String oldTrans = null; String langId = null; // Preserve translation changes if (HBM2DDL_UPDATE.equals(hbm2ddl)) { langId = FileUtils.getFileName(res); log.info("Preserving translations for: {}", langId); oldTrans = preserveTranslations(langId); } InputStream isLang = ConfigUtils.getResourceAsStream("i18n/" + res); log.info("Importing translation: {}", res); executeSentences(new InputStreamReader(isLang)); IOUtils.closeQuietly(isLang); // Apply previous translation changes if (HBM2DDL_UPDATE.equals(hbm2ddl)) { if (oldTrans != null) { log.info("Restoring translations for: {}", langId); executeSentences(new StringReader(oldTrans)); } } } // Replace "create" or "update" by "none" to prevent repository reset on restart if (Boolean.parseBoolean(Config.HIBERNATE_CREATE_AUTOFIX)) { log.info("Executing Hibernate create autofix"); hibernateCreateAutofix(Config.HOME_DIR + "/" + Config.OPENKM_CONFIG); } else { log.info("Hibernate create autofix not executed because of {}={}", Config.PROPERTY_HIBERNATE_CREATE_AUTOFIX, Config.HIBERNATE_CREATE_AUTOFIX); } } } catch (HibernateException e) { log.error(e.getMessage(), e); throw new ExceptionInInitializerError(e); } catch (URISyntaxException e) { log.error(e.getMessage(), e); throw new ExceptionInInitializerError(e); } catch (IOException e) { log.error(e.getMessage(), e); throw new ExceptionInInitializerError(e); } } return sessionFactory; }
From source file:com.plexobject.testplayer.dao.hibernate.HibernateUtil.java
License:Open Source License
/** * Rebuild the SessionFactory with the given Hibernate Configuration. * <p>// ww w . j av a 2 s . c o m * HibernateUtil does not configure() the given Configuration object, * it directly calls buildSessionFactory(). This method also closes * the old static variable SessionFactory before, if it is still open. * * @param cfg */ public static void rebuildSessionFactory(Configuration cfg) { log.debug("Rebuilding the SessionFactory from given Configuration"); if (sessionFactory != null && !sessionFactory.isClosed()) sessionFactory.close(); if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) { log.debug("Managing SessionFactory in JNDI"); cfg.buildSessionFactory(); } else { log.debug("Holding SessionFactory in static variable"); sessionFactory = cfg.buildSessionFactory(); } configuration = cfg; }
From source file:com.redhat.rhn.common.hibernate.ConnectionManager.java
License:Open Source License
/** * Create a SessionFactory, loading the hbm.xml files from the specified * location.// w w w. j a va2s .c o m * @param packageNames Package name to be searched. */ private void createSessionFactory() { if (sessionFactory != null && !sessionFactory.isClosed()) { return; } List<String> hbms = new LinkedList<String>(); for (Iterator<String> iter = packageNames.iterator(); iter.hasNext();) { String pn = iter.next(); hbms.addAll(FinderFactory.getFinder(pn).find("hbm.xml")); if (LOG.isDebugEnabled()) { LOG.debug("Found: " + hbms); } } try { Configuration config = new Configuration(); /* * Let's ask the RHN Config for all properties that begin with * hibernate.* */ LOG.info("Adding hibernate properties to hibernate Configuration"); Properties hibProperties = Config.get().getNamespaceProperties("hibernate"); hibProperties.put("hibernate.connection.username", Config.get().getString(ConfigDefaults.DB_USER)); hibProperties.put("hibernate.connection.password", Config.get().getString(ConfigDefaults.DB_PASSWORD)); hibProperties.put("hibernate.connection.url", ConfigDefaults.get().getJdbcConnectionString()); config.addProperties(hibProperties); // Force the use of our txn factory if (config.getProperty(Environment.TRANSACTION_STRATEGY) != null) { throw new IllegalArgumentException("The property " + Environment.TRANSACTION_STRATEGY + " can not be set in a configuration file;" + " it is set to a fixed value by the code"); } for (Iterator<String> i = hbms.iterator(); i.hasNext();) { String hbmFile = i.next(); if (LOG.isDebugEnabled()) { LOG.debug("Adding resource " + hbmFile); } config.addResource(hbmFile); } if (configurators != null) { for (Iterator<Configurator> i = configurators.iterator(); i.hasNext();) { Configurator c = i.next(); c.addConfig(config); } } // add empty varchar warning interceptor EmptyVarcharInterceptor interceptor = new EmptyVarcharInterceptor(); interceptor.setAutoConvert(true); config.setInterceptor(interceptor); sessionFactory = config.buildSessionFactory(); } catch (HibernateException e) { LOG.error("FATAL ERROR creating HibernateFactory", e); } }
From source file:com.sakadream.sql.SQLConfigJson.java
License:MIT License
/** * Get Hibernate Configuration Properties using Hibernate API * @param pkgLocation hibernate.cfg.xml's folder location * @return SQLConfig SQLConfig object//ww w . j a v a 2s.c o m */ public static SQLConfig getHibernateCfg(String pkgLocation) { Configuration config = new Configuration(); config.configure(pkgLocation + "hibernate.cfg.xml"); String username = config.getProperty("hibernate.connection.username"); String password = config.getProperty("hibernate.connection.password"); String url = config.getProperty("hibernate.connection.url"); SQLConfig sqlconfig = new SQLConfig(); sqlconfig.setDialect(dl.getDialectByUrl(url)); sqlconfig.setUsername(username); sqlconfig.setPassword(password); sqlconfig.setHibernateConfig(true); return sqlconfig; }
From source file:com.shyslav.controller.MyController.java
@RequestMapping(value = "/search") private String search(ModelMap mv, HttpServletRequest request, HttpSession ses) throws UnsupportedEncodingException, SQLException { request.setCharacterEncoding("UTF-8"); String searchText = request.getParameter("searchText"); String query = "select b.id as id, server_Path as server_Path,g.name as genre,\n" + "b.name as name, \n" + "b.author as author, \n" + "b.small_text as smallText,\n" + "b.full_text as fullTexts, \n" + "b.date_create as dateCreate,\n" + "b.vision as vision from books b\n" + "inner join genre g on b.genre = g.id\n" + "where (b.name like \"%" + searchText + "%\"\n" + " or g.name like \"%" + searchText + "%\"\n" + " or b.author like \"%" + searchText + "%\" )\n" + " and b.vision = '+'"; Statement st = null;//from w w w .j av a 2 s.c o m Connection con = null; ResultSet rs = null; ArrayList<Books> result = new ArrayList(); Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); try { Class.forName(cfg.getProperty("hibernate.connection.driver_class")); con = DriverManager.getConnection(cfg.getProperty("hibernate.connection.url"), cfg.getProperty("hibernate.connection.username"), cfg.getProperty("hibernate.connection.password")); st = con.createStatement(); rs = st.executeQuery(query); while (rs.next()) { result.add(new Books(new Genre(rs.getString("genre")), rs.getString("name"), rs.getString("author"), rs.getString("smallText"), rs.getString("fullTexts"), rs.getDate("dateCreate"), rs.getString("vision").charAt(0), rs.getInt("id"), rs.getString("server_Path"))); } } catch (ClassNotFoundException | SQLException ex) { System.out.println("Error" + ex); } finally { st.close(); con.close(); } standartInitialize(mv, ses); if (result.size() == 0) { mv.addAttribute("answer", "? "); } else { mv.addAttribute("books", result); } System.out.println(result.size()); return "index"; }
From source file:com.vecna.dbDiff.hibernate.HibernateMappingsConverter.java
License:Apache License
/** * Extract the dialect from a hibernate configuration. * @param hibernateConfiguration hibernate configuration. * @return the dialect object./*from w ww . j a v a 2 s. co m*/ */ private Dialect getDialect(Configuration hibernateConfiguration) { String dialectClassName = hibernateConfiguration.getProperty("hibernate.dialect"); if (dialectClassName == null) { throw new IllegalStateException("dialect is not set"); } Class<?> dialectClass; try { dialectClass = Thread.currentThread().getContextClassLoader().loadClass(dialectClassName); } catch (ClassNotFoundException e) { throw new IllegalStateException("can't load dialect class", e); } try { return (Dialect) dialectClass.newInstance(); } catch (IllegalAccessException e) { throw new IllegalStateException("can't create dialect", e); } catch (InstantiationException e) { throw new IllegalStateException("can't create dialect", e); } }