List of usage examples for org.hibernate.cfg Configuration setProperty
public Configuration setProperty(String propertyName, String value)
From source file:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java
License:Open Source License
protected SessionFactory buildSessionFactory() throws Exception { logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] BEGIN"); SessionFactory sf = null;/*from www . ja v a 2 s .c om*/ // Create Configuration instance. Configuration config = newConfiguration(); DataSource currentDataSource = getCurrentDataSource(); logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '" + RepositoryManager.getCurrentRepository() + "' -- Got currentDataSource: " + currentDataSource); if (currentDataSource == null) { throw new IllegalStateException("Null DataSource!"); } // Make given DataSource available for SessionFactory configuration. logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Thread '" + Thread.currentThread().getName() + "' -- Setting DataSource for current thread: " + currentDataSource); CONFIG_TIME_DS_HOLDER.set(currentDataSource); if (this.jtaTransactionManager != null) { // Make Spring-provided JTA TransactionManager available. CONFIG_TIME_TM_HOLDER.set(this.jtaTransactionManager); } if (this.lobHandler != null) { // Make given LobHandler available for SessionFactory configuration. // Do early because because mapping resource might refer to custom types. CONFIG_TIME_LOB_HANDLER_HOLDER.set(this.lobHandler); } try { // Set connection release mode "on_close" as default. // This was the case for Hibernate 3.0; Hibernate 3.1 changed // it to "auto" (i.e. "after_statement" or "after_transaction"). // However, for Spring's resource management (in particular for // HibernateTransactionManager), "on_close" is the better default. config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString()); if (!isExposeTransactionAwareSessionFactory()) { // Not exposing a SessionFactory proxy with transaction-aware // getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext // implementation instead, providing the Spring-managed Session that way. // Can be overridden by a custom value for corresponding Hibernate property. config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "org.springframework.orm.hibernate3.SpringSessionContext"); } if (this.entityInterceptor != null) { // Set given entity interceptor at SessionFactory level. config.setInterceptor(this.entityInterceptor); } if (this.namingStrategy != null) { // Pass given naming strategy to Hibernate Configuration. config.setNamingStrategy(this.namingStrategy); } if (this.typeDefinitions != null) { // Register specified Hibernate type definitions. Mappings mappings = config.createMappings(); for (int i = 0; i < this.typeDefinitions.length; i++) { TypeDefinitionBean typeDef = this.typeDefinitions[i]; mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters()); } } if (this.filterDefinitions != null) { // Register specified Hibernate FilterDefinitions. for (int i = 0; i < this.filterDefinitions.length; i++) { config.addFilterDefinition(this.filterDefinitions[i]); } } if (this.configLocations != null) { for (int i = 0; i < this.configLocations.length; i++) { // Load Hibernate configuration from given location. config.configure(this.configLocations[i].getURL()); } } if (this.hibernateProperties != null) { // Add given Hibernate properties to Configuration. config.addProperties(this.hibernateProperties); } if (currentDataSource != null) { boolean actuallyTransactionAware = (this.useTransactionAwareDataSource || currentDataSource instanceof TransactionAwareDataSourceProxy); // Set Spring-provided DataSource as Hibernate ConnectionProvider. config.setProperty(Environment.CONNECTION_PROVIDER, actuallyTransactionAware ? TransactionAwareDataSourceConnectionProvider.class.getName() : RoutingLocalDataSourceConnectionProvider.class.getName()); } if (this.jtaTransactionManager != null) { // Set Spring-provided JTA TransactionManager as Hibernate property. config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName()); } if (this.mappingLocations != null) { // Register given Hibernate mapping definitions, contained in resource files. for (int i = 0; i < this.mappingLocations.length; i++) { config.addInputStream(this.mappingLocations[i].getInputStream()); } } if (this.cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from the file system. for (int i = 0; i < this.cacheableMappingLocations.length; i++) { config.addCacheableFile(this.cacheableMappingLocations[i].getFile()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (int i = 0; i < this.mappingJarLocations.length; i++) { Resource resource = this.mappingJarLocations[i]; config.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (int i = 0; i < this.mappingDirectoryLocations.length; i++) { File file = this.mappingDirectoryLocations[i].getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException("Mapping directory location [" + this.mappingDirectoryLocations[i] + "] does not denote a directory"); } config.addDirectory(file); } } if (this.entityCacheStrategies != null) { // Register cache strategies for mapped entities. for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames .hasMoreElements(); /* */) { String className = (String) classNames.nextElement(); String[] strategyAndRegion = StringUtils .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]); } } } if (this.collectionCacheStrategies != null) { // Register cache strategies for mapped collections. for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles .hasMoreElements(); /* */) { String collRole = (String) collRoles.nextElement(); String[] strategyAndRegion = StringUtils .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole)); if (strategyAndRegion.length > 1) { config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]); } } } if (this.eventListeners != null) { // Register specified Hibernate event listeners. for (Map.Entry<?, ?> entry : this.eventListeners.entrySet()) { Assert.isTrue(entry.getKey() instanceof String, "Event listener key needs to be of type String"); String listenerType = (String) entry.getKey(); Object listenerObject = entry.getValue(); if (listenerObject instanceof Collection) { Collection<?> listeners = (Collection<?>) listenerObject; EventListeners listenerRegistry = config.getEventListeners(); Object[] listenerArray = (Object[]) Array .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size()); listenerArray = listeners.toArray(listenerArray); config.setListeners(listenerType, listenerArray); } else { config.setListener(listenerType, listenerObject); } } } // Perform custom post-processing in subclasses. postProcessConfiguration(config); // Build SessionFactory instance. logger.debug( "[RoutingLocalSessionFactoryBean::buildSessionFactory] Building new Hibernate SessionFactory."); this.configuration = config; SessionFactoryProxy sessionFactoryProxy = new SessionFactoryProxy( repositoryManager.getDefaultRepository().getId()); for (Repository repository : repositoryManager.getRepositories()) { logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '" + repository.getId() + "' -- Building SessionFactory..."); RepositoryManager.setCurrentRepository(repository.getId()); sessionFactoryProxy.addSessionFactory(repository.getId(), newSessionFactory(config)); } RepositoryManager.setCurrentRepository(repositoryManager.getDefaultRepository().getId()); sf = sessionFactoryProxy; } finally { if (currentDataSource != null) { // Reset DataSource holder. CONFIG_TIME_DS_HOLDER.set(null); } if (this.jtaTransactionManager != null) { // Reset TransactionManager holder. CONFIG_TIME_TM_HOLDER.set(null); } if (this.lobHandler != null) { // Reset LobHandler holder. CONFIG_TIME_LOB_HANDLER_HOLDER.set(null); } } // Execute schema update if requested. if (this.schemaUpdate) { updateDatabaseSchema(); } return sf; }
From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java
License:Open Source License
private void doBootstrap() { // do everything in a transaction Session session = getSessionFactory().openSession(); try {// ww w.j a v a 2 s . com // make sure that we AUTO-COMMIT Connection connection = session.connection(); connection.setAutoCommit(true); // DoQui workaround: getConfiguration() solleverebbe una IllegalStateException() Configuration cfg = localSessionFactory.getConfigurationOverride(); // Check and dump the dialect being used Dialect dialect = Dialect.getDialect(cfg.getProperties()); Class<?> dialectClazz = dialect.getClass(); LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_DIALECT_USED, dialectClazz.getName()); if (dialectClazz.equals(MySQLDialect.class) || dialectClazz.equals(MySQL5Dialect.class)) { LogUtil.warn( logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + WARN_DIALECT_UNSUPPORTED, dialectClazz.getName()); } if (dialectClazz.equals(HSQLDialect.class)) { logger.info("[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + I18NUtil.getMessage(WARN_DIALECT_HSQL)); } // Ensure that our static connection provider is used String defaultConnectionProviderFactoryClass = cfg.getProperty(Environment.CONNECTION_PROVIDER); cfg.setProperty(Environment.CONNECTION_PROVIDER, SchemaBootstrapConnectionProvider.class.getName()); SchemaBootstrapConnectionProvider.setBootstrapConnection(connection); // update the schema, if required if (updateSchema) { // Check and record that the bootstrap has started setBootstrapStarted(connection); // Allocate buffer for executed statements executedStatementsThreadLocal.set(new StringBuilder(1024)); updateSchema(cfg, session, connection); // Copy the executed statements to the output file File schemaOutputFile = null; if (schemaOuputFilename != null) { schemaOutputFile = new File(schemaOuputFilename); } else { schemaOutputFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-All_Statements-", ".sql"); } String executedStatements = executedStatementsThreadLocal.get().toString(); if (executedStatements.length() == 0) { LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_NO_CHANGES); } else { FileContentWriter writer = new FileContentWriter(schemaOutputFile); writer.setEncoding("UTF-8"); writer.putContent(executedStatements); LogUtil.info( logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_ALL_STATEMENTS, schemaOutputFile.getPath()); } // verify that all patches have been applied correctly checkSchemaPatchScripts(cfg, session, connection, validateUpdateScriptPatches, false); // check scripts checkSchemaPatchScripts(cfg, session, connection, preUpdateScriptPatches, false); // check scripts checkSchemaPatchScripts(cfg, session, connection, postUpdateScriptPatches, false); // check scripts // Remove the flag indicating a running bootstrap setBootstrapCompleted(connection); } else { LogUtil.info(logger, "[SchemaBootstrap::doBootstrap] Repository '" + RepositoryManager.getCurrentRepository() + "' -- " + MSG_BYPASSING_SCHEMA_UPDATE); } // Reset the configuration cfg.setProperty(Environment.CONNECTION_PROVIDER, defaultConnectionProviderFactoryClass); // all done successfully } catch (Throwable e) { LogUtil.error(logger, e, ERR_UPDATE_FAILED); if (updateSchema) { throw new AlfrescoRuntimeException(ERR_UPDATE_FAILED, e); } else { throw new AlfrescoRuntimeException(ERR_VALIDATION_FAILED, e); } } finally { // Remove the connection reference from the threadlocal boostrap SchemaBootstrapConnectionProvider.setBootstrapConnection(null); } }
From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.SchemaBootstrap.java
License:Open Source License
private static void dumpDialectScript(Configuration configuration, Class<?> dialectClazz, File directory) { // Set the dialect configuration.setProperty("hibernate.dialect", dialectClazz.getName()); // First dump the dialect's schema String filename = "default-schema-create-" + dialectClazz.getName() + ".sql"; File dumpFile = new File(directory, filename); // Write the file SchemaBootstrap.dumpSchemaCreate(configuration, dumpFile); }
From source file:it.eng.qbe.datasource.hibernate.HibernateDataSource.java
License:Mozilla Public License
protected Configuration buildEmptyConfiguration() { Configuration cfg = null; cfg = new Configuration(); ConnectionDescriptor connection = getConnection(); if (connection.isJndiConncetion()) { cfg.setProperty("hibernate.connection.datasource", connection.getJndiName()); cfg.setProperty("hibernate.validator.apply_to_ddl", "false"); cfg.setProperty("hibernate.validator.autoregister_listeners", "false"); } else {//w w w .j ava 2 s . c om cfg.setProperty("hibernate.connection.url", connection.getUrl()); cfg.setProperty("hibernate.connection.password", connection.getPassword()); cfg.setProperty("hibernate.connection.username", connection.getUsername()); cfg.setProperty("hibernate.connection.driver_class", connection.getDriverClass()); cfg.setProperty("hibernate.validator.apply_to_ddl", "false"); cfg.setProperty("hibernate.validator.autoregister_listeners", "false"); } cfg.setProperty("hibernate.dialect", connection.getDialect()); // Ingres does not support scrollable result set if ("org.hibernate.dialect.IngresDialect".equals(connection.getDialect())) { cfg.setProperty("hibernate.jdbc.use_scrollable_resultset", "false"); } cfg.setProperty("hibernate.cglib.use_reflection_optimizer", "true"); cfg.setProperty("hibernate.show_sql", "false"); return cfg; }
From source file:it.eng.spagobi.tools.importexport.ExportUtilities.java
License:Mozilla Public License
/** * Creates an Hibernate session factory for the export database. * /*from ww w . ja v a 2s. co m*/ * @param pathDBFolder Path of the export database folder * * @return The Hibernate Session Factory * * @throws EMFUserError the EMF user error */ public static SessionFactory getHibSessionExportDB(String pathDBFolder) throws EMFUserError { logger.debug("IN"); Configuration conf = new Configuration(); String resource = "it/eng/spagobi/tools/importexport/metadata/hibernate.cfg.hsql.export.xml"; conf = conf.configure(resource); String hsqlJdbcString = "jdbc:hsqldb:file:" + pathDBFolder + "/metadata;shutdown=true"; conf.setProperty("hibernate.connection.url", hsqlJdbcString); SessionFactory sessionFactory = conf.buildSessionFactory(); logger.debug("OUT"); return sessionFactory; }
From source file:it.eng.spagobi.tools.importexport.ImportUtilities.java
License:Mozilla Public License
/** * Creates an Hibernate session factory for the exported database. * /*from w w w . j av a2 s .c om*/ * @param pathDBFolder The path of the folder which contains the exported database * * @return The Hibernate session factory * * @throws EMFUserError the EMF user error */ public static SessionFactory getHibSessionExportDB(String pathDBFolder) throws EMFUserError { logger.debug("IN"); Configuration conf = new Configuration(); String resource = "it/eng/spagobi/tools/importexport/metadata/hibernate.cfg.hsql.export.xml"; conf = conf.configure(resource); String hsqlJdbcString = "jdbc:hsqldb:file:" + pathDBFolder + "/metadata;shutdown=true"; conf.setProperty("hibernate.connection.url", hsqlJdbcString); SessionFactory sessionFactory = conf.buildSessionFactory(); logger.debug("IN"); return sessionFactory; }
From source file:it.jrc.smart.fire.job.TestHibernateSessionManager.java
License:Open Source License
private static final void createSessionFactory() { if (sessionFactory == null) { URL resource = Thread.currentThread().getContextClassLoader().getResource("hibernate.cfg.xml"); Configuration config = new Configuration().configure(resource); config.setProperty("hibernate.connection.username", "smart_admin"); config.setProperty("hibernate.connection.password", "smart_derby"); //add mapping classes CacheConfiguration c;// ww w .j a v a 2 s .c o m config.addAnnotatedClass(ConservationArea.class); config.addAnnotatedClass(Area.class); config.addAnnotatedClass(Language.class); config.addAnnotatedClass(Employee.class); config.addAnnotatedClass(Rank.class); config.addAnnotatedClass(Agency.class); config.addAnnotatedClass(Label.class); config.addAnnotatedClass(DmObject.class); config.addAnnotatedClass(Category.class); config.addAnnotatedClass(Attribute.class); config.addAnnotatedClass(CategoryAttribute.class); config.addAnnotatedClass(Aggregation.class); config.addAnnotatedClass(AttributeListItem.class); config.addAnnotatedClass(AttributeTreeNode.class); config.addAnnotatedClass(org.wcs.smart.ca.Projection.class); config.addAnnotatedClass(org.wcs.smart.observation.model.WaypointObservation.class); config.addAnnotatedClass(org.wcs.smart.observation.model.Waypoint.class); config.addAnnotatedClass(org.wcs.smart.observation.model.WaypointObservationAttribute.class); config.addAnnotatedClass(org.wcs.smart.observation.model.ObservationAttachment.class); config.addAnnotatedClass(org.wcs.smart.observation.model.WaypointAttachment.class); config.addAnnotatedClass(org.wcs.smart.observation.model.ObservationOptions.class); sessionFactory = config.buildSessionFactory(); if (!((SessionFactoryImplementor) sessionFactory).getDialect().supportsSequences()) { //fail throw new IllegalStateException("You can't use this database - it does not support sequences"); } } }
From source file:it.openprj.jValidator.spring.ApplicationConfigCreateController.java
License:Open Source License
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Create create = new Create(); ServletOutputStream out = null;// w w w . j av a 2 s . c o m response.setContentType("application/json"); out = response.getOutputStream(); String configType = request.getParameter("configType"); if (configType.equals("database")) { if (checkDatabaseConnection(request)) { ApplicationConfigEntity appConfigEntity = new ApplicationConfigEntity(); appConfigEntity.setConfigType(ApplicationConfigType.DATABASE); appConfigEntity.setDatabaseName(request.getParameter("databaseName")); appConfigEntity.setHost(request.getParameter("host")); appConfigEntity.setIdDatabaseType(Integer.parseInt(request.getParameter("idDatabaseType"))); appConfigEntity.setPassword(request.getParameter("password")); appConfigEntity.setPort(request.getParameter("port")); appConfigEntity.setUserName(request.getParameter("userName")); try { Configuration conf = new Configuration().configure(); conf.setProperty("hibernate.connection.url", em.getEntityManagerFactory().getProperties().get("hibernate.connection.url") + "?relaxAutoCommit=" + em.getEntityManagerFactory().getProperties() .get("hibernate.connection.autocommit")); new SchemaExport(conf).create(true, true); } catch (Exception ex) { //ex.printStackTrace(); } create = applicationConfigDao.create(appConfigEntity); } else { create.setMessage(I18n.getMessage("error.databaseConnectionError")); create.setSuccess(false); } } else if (configType.equals("userProfile")) { String userName = request.getParameter("userName"); String password = request.getParameter("password"); String name = request.getParameter("name"); String email = request.getParameter("email"); long idAlert = Long .parseLong(request.getParameter("idAlert").isEmpty() ? "0" : request.getParameter("idAlert")); String surname = request.getParameter("surname"); String language = request.getParameter("language"); String dob = request.getParameter("dob"); Date date = null; if (dob != null && dob.trim().length() > 0) { try { date = new SimpleDateFormat("dd/MMM/yyyy").parse(dob); } catch (Exception ex) { ex.printStackTrace(); } } UserEntity userEntity = new UserEntity(userName, password, name, surname, email, 1, 1, language, idAlert, -1, date, "neptune"); create = usersDao.create(userEntity); create.setMessage(I18n.getMessage("success.userProfileSaved")); } else if (configType.equals("ftp")) { ApplicationConfigEntity appConfigEntity = new ApplicationConfigEntity(); appConfigEntity.setConfigType(ApplicationConfigType.FTP); appConfigEntity.setUserName(request.getParameter("userName")); appConfigEntity.setPassword(request.getParameter("password")); appConfigEntity.setInputDir(request.getParameter("inputDirectory")); appConfigEntity.setOutputDir(request.getParameter("outputDirectory")); create = applicationConfigDao.create(appConfigEntity); create.setMessage(I18n.getMessage("success.ftpConfigSaved")); } else if (configType.equals("email")) { ApplicationConfigEntity appConfigEntity = new ApplicationConfigEntity(); String serverUrl = getServerURL(request.getRequestURL().toString()); if (!serverUrl.equals("")) { appConfigEntity.setConfigType(ApplicationConfigType.APPLURL); appConfigEntity.setHost(serverUrl); System.out.println(request.getRequestURL().toString()); create = applicationConfigDao.create(appConfigEntity); appConfigEntity = new ApplicationConfigEntity(); } appConfigEntity.setConfigType(ApplicationConfigType.EMAIL); appConfigEntity.setUserName(request.getParameter("userName")); appConfigEntity.setPassword(request.getParameter("password")); appConfigEntity.setHost(request.getParameter("host")); appConfigEntity.setPort(request.getParameter("port")); appConfigEntity.setProtocol(request.getParameter("protocol")); appConfigEntity.setEncoding(request.getParameter("encoding")); appConfigEntity.setSmtpsTimeout(request.getParameter("smtpstimeout")); appConfigEntity.setIsStarTtls(Integer .parseInt(request.getParameter("starttls") == null ? "0" : request.getParameter("starttls"))); appConfigEntity .setIsSmtpsAuthenticate(Integer.parseInt(request.getParameter("smtpsAuthenticate") == null ? "0" : request.getParameter("smtpsAuthenticate"))); create = applicationConfigDao.create(appConfigEntity); create.setMessage(I18n.getMessage("success.emailConfigSaved")); } ObjectMapper mapper = new ObjectMapper(); out.write(mapper.writeValueAsBytes(create)); out.flush(); out.close(); return null; }
From source file:iu.slam.database.DatabaseHandler.java
License:Open Source License
private DatabaseHandler() { Configuration configuration = new Configuration(); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver"); configuration.setProperty("hibernate.connection.url", "jdbc:mysql://127.0.0.1:3306/slam?autoReconnect=true");//3306 wamp mysql configuration.setProperty("hibernate.connection.username", "root"); configuration.setProperty("hibernate.connection.password", ""); //configuration.setProperty("hibernate.format_sql", "true"); //configuration.setProperty("hibernate.show_sql", "true"); configuration.setProperty("hibernate.connection.provider_class", "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider"); configuration.setProperty("hibernate.c3p0.idleConnectionTestPeriod", "600"); configuration.setProperty("hibernate.c3p0.testConnectionOnCheckin", "true"); configuration.addAnnotatedClass(SensorData.class).addAnnotatedClass(Experiment.class) .addAnnotatedClass(Photo.class).addAnnotatedClass(Video.class).addAnnotatedClass(PhotoTags.class) .addAnnotatedClass(PhotoDrawTag.class); sessionFactory = configuration.buildSessionFactory( new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry()); sessionFactory.getStatistics().setStatisticsEnabled(true); UtilLog.logDatabase(DatabaseHandler.class, "SessionFactory created"); }
From source file:jgamebase.db.Db.java
License:Open Source License
public static synchronized void init(final String dbName, final boolean createDb) { try {//from w w w . jav a 2s. c o m org.hibernate.cfg.Configuration config; if (session != null) { close(); } if (createDb) { // create db log.info("\nCreating database '" + dbName + "'..."); // Create the SessionFactory from hibernateImport.cfg.xml config = new org.hibernate.cfg.Configuration() .configure(new File(Const.GBDIR_RO, "hibernateImport.cfg.xml")); // Database connection settings config.setProperty("hibernate.connection.driver_class", dbDriver); config.setProperty("hibernate.default_schema", "APP"); config.setProperty("hibernate.connection.url", dbUrl + new File(new File(Const.GBDIR_RW, dbName), Const.DATABASE_DIRNAME) + ";create=true"); config.setProperty("hbm2ddl.auto", "create"); } else { // open db log.info("\nOpening database '" + dbName + "'..."); // Create the SessionFactory from hibernate.cfg.xml config = new org.hibernate.cfg.Configuration() .configure(new File(Const.GBDIR_RO, "hibernate.cfg.xml")); // Database connection settings config.setProperty("hibernate.connection.driver_class", dbDriver); config.setProperty("hibernate.default_schema", "APP"); config.setProperty("hibernate.connection.url", dbUrl + new File(new File(Const.GBDIR_RW, dbName), Const.DATABASE_DIRNAME)); } sessionFactory = config.buildSessionFactory(); session = sessionFactory.openSession(); if (!createDb) { // reorganize(); final double version = getVersion(); if (version == 0.0) { log.info("Warning: Could not read database version."); Gui.displayWarningDialog("Could not read database version."); } else if (version < Db.NEEDED_VERSION) { // update database log.info("\nFound database in version " + version + ", but need version " + NEEDED_VERSION + ": trying to update it...\n"); // export existing data into .csv files Export.db2Csv(getTableNames()); // shutdown database driver shutdown(); // delete old database directory log.info("\nDeleting old database directory '" + new File(new File(Const.GBDIR_RW, dbName), Const.DATABASE_DIRNAME) + "'.\n"); FileTools.deleteAll(new File(new File(Const.GBDIR_RW, dbName), Const.DATABASE_DIRNAME)); // update .csv files to current database schema final boolean errorOccured = Update.updateFrom(Databases.getCurrent().getExportPath(), version); if (errorOccured) { log.info("ERROR: Could not update database to version " + NEEDED_VERSION + "."); Gui.displayErrorDialog("Could not update database to version " + NEEDED_VERSION + "."); JGameBase.quit(); } // reload database driver Class.forName(dbDriver).newInstance(); // create empty database Db.init(dbName, true); // import .csv files Import.csv2Db(Databases.getCurrent().getExportPath()); log.info("DB Converted."); // close and reopen database close(); Db.init(dbName, false); } } if (!getTableNames().contains("VIEWCOLUMNS")) { try { log.info("\nTable 'VIEWCOLUMNS' does not exist, trying to create it..."); createTable_ViewColumns(); log.info("Table successfully created.\n"); } catch (final Exception e) { log.info("Table could NOT be created!\n"); e.printStackTrace(); } } } catch (final Throwable ex) { // Make sure you out the exception, as it might be swallowed log.error("Initial SessionFactory or Session creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } }