List of usage examples for org.hibernate.cfg Configuration setProperty
public Configuration setProperty(String propertyName, String value)
From source file:edu.pitt.dbmi.facebase.hd.MySQLHibernateConfiguration.java
License:Open Source License
private SessionFactory getSessionFactory() { log.debug("MySQLHibernateConfiguration.getSessionFactory() called "); if (lclSessionFactory != null) return (lclSessionFactory); try {/* w w w .j a v a2s . c o m*/ boolean validConnection = false; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Connection conn = DriverManager.getConnection(connectionURL, username, password); conn.close(); validConnection = true; } catch (Exception e) { String errorString = "Cannot connect to database at " + connectionURL + " with username " + username + e.toString(); String logString = e.getMessage(); edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString); log.error(errorString, e); edu.pitt.dbmi.facebase.hd.HumanDataController.reportDbConnectionFailure(); return (null); } if (validConnection) { Configuration hibernateConf = null; hibernateConf = new Configuration(); String className = null; try { hibernateConf.addAnnotatedClass(InstructionQueueItem.class); } catch (Exception ex) { String errorString = "Unable to load annotated class for hibernate: " + className + ex.toString(); String logString = ex.getMessage(); edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString); edu.pitt.dbmi.facebase.hd.HumanDataController.reportDbConnectionFailure(); log.error("Unable to load annotated class for hibernate: " + className, ex); } hibernateConf.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.url", connectionURL) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect") .setProperty("hibernate.connection.username", username) .setProperty("hibernate.connection.password", password) .setProperty("hibernate.show_sql", "false") .setProperty("hibernate.current_session_context_class", "thread") .setProperty("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider") .setProperty("hibernate.c3p0.acquire_increment", "1") .setProperty("hibernate.c3p0.idle_test_period", "240") .setProperty("hibernate.c3p0.timeout", "600").setProperty("hibernate.c3p0.max_size", "100") .setProperty("hibernate.c3p0.min_size", "3") .setProperty("hibernate.c3p0.validate", "false") /*this is an expensive property to turn on...*/ .setProperty("hibernate.c3p0.max_statements", "500") .setProperty("hibernate.cache.use_second_level_cache", "false") .setProperty("hibernate.jdbc.batch.size", "20"); lclSessionFactory = hibernateConf.buildSessionFactory(); } } catch (Throwable ex) { String errorString = "Initial SessionFactory creation failed." + ex.toString(); String logString = ex.getMessage(); edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString); edu.pitt.dbmi.facebase.hd.HumanDataController.reportDbConnectionFailure(); log.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } return (lclSessionFactory); }
From source file:edu.pitt.dbmi.facebase.hd.MySQLHibernateConfigurationHd.java
License:Open Source License
private SessionFactory getSessionFactory() { log.debug("MySQLHibernateConfigurationHd.getSessionFactory() called."); if (lclSessionFactoryHd != null) return (lclSessionFactoryHd); try {// www.ja v a 2 s.c om boolean validConnection = false; try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Connection conn = DriverManager.getConnection(connectionURL, username, password); conn.close(); validConnection = true; } catch (Exception e) { String errorString = "Cannot connect to database at " + connectionURL + " with username " + username; String logString = e.getMessage(); edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString); log.error(errorString, e); return (null); } if (validConnection) { Configuration hibernateConfHd = null; hibernateConfHd = new Configuration(); String className = null; try { hibernateConfHd.addAnnotatedClass(FbKey.class); } catch (Exception ex) { String errorString = "Unable to load annotated class for hibernate: " + className; String logString = ex.getMessage(); edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString); log.error(errorString, ex); } hibernateConfHd.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") .setProperty("hibernate.connection.url", connectionURL) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect") .setProperty("hibernate.connection.username", username) .setProperty("hibernate.connection.password", password) .setProperty("hibernate.show_sql", "false") .setProperty("hibernate.current_session_context_class", "thread") .setProperty("hibernate.connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider") .setProperty("hibernate.c3p0.acquire_increment", "1") .setProperty("hibernate.c3p0.idle_test_period", "240") .setProperty("hibernate.c3p0.timeout", "600").setProperty("hibernate.c3p0.max_size", "100") .setProperty("hibernate.c3p0.min_size", "3") .setProperty("hibernate.c3p0.validate", "false") /*this is an expensive property to turn on...*/ .setProperty("hibernate.c3p0.max_statements", "500") .setProperty("hibernate.cache.use_second_level_cache", "false") .setProperty("hibernate.jdbc.batch.size", "20"); lclSessionFactoryHd = hibernateConfHd.buildSessionFactory(); } } catch (Throwable ex) { String errorString = "Initial SessionFactory creation failed."; String logString = ex.getMessage(); edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString); log.error(errorString, ex); throw new ExceptionInInitializerError(ex); } return (lclSessionFactoryHd); }
From source file:example.hibernatetool.SpringComponentConfiguration.java
License:Apache License
private void initializeDataSource(Configuration config) { String beanName = getExporterMojo().getComponentProperty("datasourcebean", "dataSource"); DataSource ds = (DataSource) applicationContext.getBean(beanName); PrivateConnectionProvider.dataSourceToUse = ds; config.setProperty(Environment.CONNECTION_PROVIDER, PrivateConnectionProvider.class.getName()); }
From source file:ezbake.data.postgres.hibernate.HibernateUtil.java
License:Apache License
private static SessionFactory buildSessionFactory(Properties ezConfig, EzSecurityToken token, SessionType sessionType) {// w w w . j av a 2s .c om try { String appName = ezConfig.getProperty(EzBakePropertyConstants.EZBAKE_APPLICATION_NAME); switch (sessionType) { case EZBAKE: { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); for (Map.Entry<Object, Object> entry : ezConfig.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); configuration.setProperty("hibernate.connection." + key, value); } return configuration .setProperty("hibernate.connection.driver_class", "ezbake.data.postgres.EzPostgresDriver") .setProperty("hibernate.connection.username", ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_USERNAME)) .setProperty("hibernate.connection.password", ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PASSWORD)) .setProperty("hibernate.connection.url", String.format("jdbc:ezbake:postgresql://%s:%s/%s", ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_HOST), ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PORT), appName)) .setProperty("hibernate.default_schema", "public") .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect") .setProperty("EzSecurityToken", new String(Base64.encodeBase64(new TSerializer().serialize(token)), Charsets.US_ASCII)) .setProperty("hibernate.hbm2ddl.auto", "update").configure().buildSessionFactory(); } case POSTGRES: { return new Configuration().setProperty("hibernate.connection.driver_class", "org.postgresql.Driver") .setProperty("hibernate.connection.username", ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_USERNAME)) .setProperty("hibernate.connection.password", ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PASSWORD)) .setProperty("hibernate.connection.url", String.format("jdbc:postgresql://%s:%s/%s", ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_HOST), ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PORT), appName)) .setProperty("hibernate.default_schema", "public") .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect") .setProperty("hibernate.show_sql", "true").setProperty("hibernate.hbm2ddl.auto", "update") .configure().buildSessionFactory(); } default: { throw new Exception("Invalid session type [" + sessionType + "]."); } } } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
From source file:functionaltests.service.SchedulerDbManagerRecoveryTest.java
License:Open Source License
private SchedulerDBManager createDatabase(boolean wipeOnStartup) throws URISyntaxException { String configureFilename = "hibernate-update.cfg.xml"; if (wipeOnStartup) { configureFilename = "hibernate.cfg.xml"; }//from ww w. ja v a 2s.c o m Configuration config = new Configuration().configure( new File(this.getClass().getResource("/functionaltests/config/" + configureFilename).toURI())); if (config.getProperty("hibernate.connection.url").contains(HsqldbServer.HSQLDB)) { String jdbcUrl = "jdbc:hsqldb:file:" + dbFolder.getRoot().getAbsolutePath() + ";create=true;hsqldb.tx=mvcc;hsqldb.write_delay=false"; config.setProperty("hibernate.connection.url", jdbcUrl); } return new SchedulerDBManager(config, wipeOnStartup); }
From source file:gov.nih.nci.security.system.ApplicationSessionFactory.java
License:Open Source License
public static SessionFactory getSessionFactory(String applicationContextName, HashMap connectionProperties) throws CSConfigurationException { SessionFactory sessionFactory = null; sessionFactory = (SessionFactory) appSessionFactories.get(applicationContextName); if (sessionFactory == null) { try {//from w w w . j a va 2s.c o m Configuration configuration = new Configuration(); configuration.addResource( "gov/nih/nci/security/authorization/domainobjects/InstanceLevelMappingElement.hbm.xml"); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Privilege.hbm.xml"); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml"); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/FilterClause.hbm.xml"); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Role.hbm.xml"); configuration.addResource("gov/nih/nci/security/dao/hibernate/RolePrivilege.hbm.xml"); configuration.addResource("gov/nih/nci/security/dao/hibernate/UserGroup.hbm.xml"); configuration .addResource("gov/nih/nci/security/dao/hibernate/ProtectionGroupProtectionElement.hbm.xml"); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Group.hbm.xml"); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/User.hbm.xml"); configuration .addResource("gov/nih/nci/security/authorization/domainobjects/ProtectionGroup.hbm.xml"); configuration .addResource("gov/nih/nci/security/authorization/domainobjects/ProtectionElement.hbm.xml"); configuration.addResource( "gov/nih/nci/security/authorization/domainobjects/UserGroupRoleProtectionGroup.hbm.xml"); configuration.addResource( "gov/nih/nci/security/authorization/domainobjects/UserProtectionElement.hbm.xml"); configuration.setProperty("hibernate.connection.url", (String) connectionProperties.get("hibernate.connection.url")); configuration.setProperty("hibernate.connection.username", (String) connectionProperties.get("hibernate.connection.username")); configuration.setProperty("hibernate.connection.password", (String) connectionProperties.get("hibernate.connection.password")); configuration.setProperty("hibernate.dialect", (String) connectionProperties.get("hibernate.dialect")); configuration.setProperty("hibernate.connection.driver_class", (String) connectionProperties.get("hibernate.connection.driver_class")); configuration.setProperty("hibernate.c3p0.min_size", "5"); configuration.setProperty("hibernate.c3p0.max_size", "20"); configuration.setProperty("hibernate.c3p0.timeout", "300"); configuration.setProperty("hibernate.c3p0.max_statements", "50"); configuration.setProperty("hibernate.c3p0.idle_test_period", "3000"); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { throw new CSConfigurationException( "Error in initializing the hibernate session factory using the provided connection parameters", e); } appSessionFactories.put(applicationContextName, sessionFactory); } return sessionFactory; }
From source file:gov.nih.nci.security.upt.util.HibernateHelper.java
License:BSD License
public static SessionFactory loadSessionFactory(String fileName, HttpSession sess) throws CSConfigurationException { FileLoader fileLoader = FileLoader.getInstance(); InputStream stream = fileLoader.getFileAsStream(fileName); SessionFactory sessionFactory = null; try {/*w w w . j a va 2 s.com*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(stream); //File file = new File(url.toURI()); //AnnotationConfiguration configuration = new AnnotationConfiguration().configure(doc); Configuration configuration = new Configuration().configure(doc); if (configuration.getProperty("hibernate.cache.use_second_level_cache") == null || configuration.getProperty("cache.use_second_level_cache") == null) { configuration.setProperty("hibernate.cache.use_second_level_cache", "false"); configuration.setProperty("cache.use_second_level_cache", "false"); } JDBCHelper.testConnectionHibernate(configuration); sessionFactory = configuration.buildSessionFactory(); } catch (CacheException e) { e.printStackTrace(); ClassPathLoader.releaseJarsFromClassPath(sess); throw new CSConfigurationException( "Error in loading the Session Factory from the Hibernate File." + e.getMessage()); } catch (Exception exception) { exception.printStackTrace(); throw new CSConfigurationException( "Error in loading the Session Factory from the Hibernate File." + exception.getMessage()); } if (null == sessionFactory) throw new CSConfigurationException("Error in loading the Session Factory from the Hibernate File"); else { Session session = null; try { session = sessionFactory.openSession(); } catch (Exception exception) { exception.printStackTrace(); throw new CSConfigurationException("Error in creating a Session from the Loaded Session Factory"); } if (null == session) throw new CSConfigurationException("Error in creating a Session from the Loaded Session Factory"); } return sessionFactory; }
From source file:gov.nih.nci.security.upt.util.JDBCHelper.java
License:BSD License
/** * This method uses Hibernates SessionFactory to get a Session and using Hibernates Criteria does a sample query * to connection and obtain results as part of testing for successful connection. * * Based on the kind of exceptions this method throws CSException with appropriate message. * @param appForm -/*from w ww . jav a2s . com*/ * The ApplicationForm with application database parameters to * test connection for. * @return String - The message indicating that connection and a SQL query * was successful * @throws CSException - * The exception message indicates which kind of application * database parameters are invalid. */ public static String testConnectionHibernate(BaseDBForm appForm) throws CSException { ApplicationForm appform = (ApplicationForm) appForm; SessionFactory sf = null; try { Configuration configuration = new Configuration(); configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml"); configuration.setProperty("hibernate.connection.url", appform.getApplicationDatabaseURL()); configuration.setProperty("hibernate.connection.username", appform.getApplicationDatabaseUserName()); configuration.setProperty("hibernate.connection.password", appform.getApplicationDatabasePassword()); configuration.setProperty("hibernate.dialect", appform.getApplicationDatabaseDialect()); configuration.setProperty("hibernate.connection.driver_class", appform.getApplicationDatabaseDriver()); configuration.setProperty("hibernate.connection.pool_size", "1"); sf = configuration.buildSessionFactory(); Session session = sf.openSession(); Criteria criteria = session.createCriteria(ApplicationContext.class); criteria.add(Expression.eq("applicationName", appform.getApplicationName().trim())); criteria.setProjection(Projections.rowCount()); List results = criteria.list(); Integer integer = (Integer) results.iterator().next(); if (integer == null) { session.close(); throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED); } session.close(); return DisplayConstants.APPLICATION_DATABASE_CONNECTION_SUCCESSFUL; } catch (Throwable t) { // Depending on the cause of the exception obtain message and throw a CSException. if (t instanceof SQLGrammarException) { throw new CSException( DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED + " " + t.getCause().getMessage()); } if (t instanceof JDBCConnectionException) { if (t.getCause() instanceof CommunicationsException) { throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED_URL_SERVER_PORT); } if (t.getCause() instanceof SQLException) { throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED_URL); } throw new CSException( DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED + " " + t.getMessage()); } if (t instanceof GenericJDBCException) { throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED_URL_USER_PASS); } if (t instanceof HibernateException) { throw new CSException( DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED + " " + t.getMessage()); } throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED); } }
From source file:gr.abiss.calipso.hibernate.SchemaHelper.java
License:Open Source License
/** * create tables using the given Hibernate configuration *//*from www .j av a 2s .c o m*/ public void updateSchema() { Configuration cfg = new Configuration(); if (StringUtils.hasText(dataSourceJndiName)) { cfg.setProperty("hibernate.connection.datasource", dataSourceJndiName); } else { cfg.setProperty("hibernate.connection.driver_class", driverClassName); cfg.setProperty("hibernate.connection.url", url); cfg.setProperty("hibernate.connection.username", username); cfg.setProperty("hibernate.connection.password", password); } cfg.setProperty("hibernate.dialect", hibernateDialect); for (String resource : mappingResources) { cfg.addResource(resource); } logger.info("begin database schema creation ========================="); new SchemaUpdate(cfg).execute(true, true); logger.info("end database schema creation ==========================="); }
From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateConfigurations.java
License:Open Source License
/** * Creates a SessionFactory.// w w w.j av a 2 s . co m * * @param pathToCfg * Path to the hibernate configuration file. * @param dbSchema * Db schema. * @param sessionInterceptor * Hibernate session interceptor. * @param hibernateMappingsPath * Path to file that lists files indexing hbm files this session factory * should be configured with * * @return Returns the session factory. * * @throws InitializationException * If the creation of the SessionFactory fails. */ @SuppressWarnings("nls") static SessionFactory createSessionFactory(String pathToCfg, String dbSchema, String sessionInterceptor, String hibernateMappingsPath) throws InitializationException { try { Configuration conf = new Configuration(); Interceptor interceptor = getInterceptor(sessionInterceptor); if (interceptor != null) { conf.setInterceptor(interceptor); } conf.setProperty(SCHEMA_PROPERTY, dbSchema); List<String> hbms = getHibernateMappingsIfAvailable(hibernateMappingsPath); for (String entityMapping : hbms) { LOGGER.debug("Adding " + entityMapping + " to the session factory configuration."); conf.addResource(entityMapping); } conf.configure(pathToCfg); conf.getEntityTuplizerFactory().registerDefaultTuplizerClass(EntityMode.POJO, Bo2PojoEntityTuplizer.class); SessionFactory sessionFactory = conf.buildSessionFactory(); ((SessionFactoryImpl) sessionFactory).registerEntityNameResolver(Bo2EntityNameResolver.INSTANCE, EntityMode.POJO); sessionFactory.getStatistics().setStatisticsEnabled(true); return sessionFactory; } catch (HibernateException e) { throw new InitializationException(e); } }