Example usage for org.hibernate.cfg Configuration setProperty

List of usage examples for org.hibernate.cfg Configuration setProperty

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration setProperty.

Prototype

public Configuration setProperty(String propertyName, String value) 

Source Link

Document

Set a property value by name

Usage

From source file:com.pymegest.persistence.hibernate.HibernateUtil.java

License:GNU General Public License

public static synchronized void buildSessionFactory() {
    if (sessionFactory == null) {
        Configuration configuration = new Configuration();
        configuration.configure();//from  w  w w.  ja  v  a 2s .  com
        configuration.setProperty("hibernate.current_session_context_class", "thread");
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
}

From source file:com.rapid.develop.core.system.dal.SessionFactoryBuilder.java

License:Apache License

/**
 * System./* ww w  .  j a v  a 2  s . co m*/
 *
 * <p>Javassit??</p>
 *
 * @return SessionFactory
 */
public synchronized SessionFactory getEntitySessionFactory() {
    if (this.entitySessionFactory == null) {
        URL url = SessionFactoryBuilder.class.getResource(AppConfigure.HIBERNATE_CFG_XML);
        Configuration configuration = new Configuration().configure(url);
        AppConfigure appConfigure = AppConfigure.loadConfig();
        for (String key : appConfigure.getConfigurationValues().keySet()) {
            configuration.setProperty(key, appConfigure.getConfigurationValues().get(key));
        }
        configuration.setProperty("hibernate.hbm2ddl.auto", "create");
        configuration.addAnnotatedClass(Application.class);
        configuration.addAnnotatedClass(AppPlugin.class);
        configuration.addAnnotatedClass(AppPluginConfig.class);
        configuration.addAnnotatedClass(AppRestService.class);
        configuration.addAnnotatedClass(AppServiceClass.class);
        configuration.addAnnotatedClass(EntityDefination.class);
        configuration.addAnnotatedClass(FieldDefination.class);
        entitySessionFactory = configuration.buildSessionFactory();
    }
    return this.entitySessionFactory;
}

From source file:com.rdsic.pcm.common.HibernateUtil.java

private static void initSessionFactory(String cfgFile) {
    if (sessionFactory == null) {
        try {//from ww w  .  j av a  2s  .  co m
            System.out.println("Loading hibernate configuration...");

            org.hibernate.cfg.Configuration hconfig = new org.hibernate.cfg.Configuration().configure(cfgFile);

            hconfig.setProperty("hibernate.connection.driver_class",
                    Configuration.getString(Constant.CONFIG_KEY.PCM_DB_DRIVER));
            hconfig.setProperty("hibernate.connection.url",
                    Configuration.getString(Constant.CONFIG_KEY.PCM_DB_URL));
            hconfig.setProperty("hibernate.connection.username",
                    Configuration.getString(Constant.CONFIG_KEY.PCM_DB_USER));
            hconfig.setProperty("hibernate.connection.password",
                    Configuration.getString(Constant.CONFIG_KEY.PCM_DB_PASSWORD));
            sessionFactory = hconfig.buildSessionFactory();

            System.out.println("Hibernate load completed...");
        } catch (Throwable ex) {
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
}

From source file:com.sakadream.sql.SQLConfigJson.java

License:MIT License

/**
 * Set hibernate.cfg.xml properties from SQLConfig object
 * @param config SQLConfig object/*w  w w.  ja v a2s  .  co  m*/
 * @param pkgLocation hibernate.cfg.xml's folder location
 */
public static void setHibernateCfg(SQLConfig config, String pkgLocation) {
    String url = "";
    if (config.getUrl() == null) {
        url = config.generateURL();
    } else {
        url = config.getUrl();
    }

    Configuration HBMconfig = new Configuration();
    HBMconfig.configure(pkgLocation + "hibernate.cfg.xml");
    HBMconfig.setProperty("hibernate.connection.username", config.getUsername());
    HBMconfig.setProperty("hibernate.connection.password", config.getPassword());
    HBMconfig.setProperty("hibernate.connection.url", url);
}

From source file:com.sap.data.db.dao.HibernateUtil.java

public static void incarnate(String entity, String firstLoad) throws NotFoundException {
    synchronized (lockUtil) {
        try {//  ww w.java2 s  .co  m
            Configuration configuration = configuration(firstLoad);
            if (null != entity && null != configuration) {
                if (null == configuration.getClassMapping(entity)) {
                    if (StructureUtil.exist(entity)) {
                        configuration.addResource(PropertyUtil.getHbPjResource() + entity + ".dto.xml");
                        configuration.setProperty(Environment.FORMAT_SQL, "true");
                        if ("true".equals(PropertyUtil.getShowSql())) {
                            configuration.setProperty(Environment.SHOW_SQL, "true");
                        }
                        SchemaUpdate su = new SchemaUpdate(configuration);
                        su.execute(true, true);
                        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                                .applySettings(configuration.getProperties()).buildServiceRegistry();
                        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
                        threadLocal.set(configuration);
                    } else {
                        throw new NotFoundException(
                                PropertyUtil.getHbPjResource() + entity + ".dto.xml not exist.");
                    }
                }
            }
        } catch (Exception ex) {
            throw new NotFoundException(ex.getMessage());
        }
    }
}

From source file:com.seer.datacruncher.spring.ApplicationConfigCreateController.java

License:Open Source License

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Create create = new Create();

    ServletOutputStream out = null;/*from w  w w  .  j a  v  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, "classic");
        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"));
        try {
            appConfigEntity.setServerPort(Integer.parseInt(request.getParameter("serverPort")));
            create = applicationConfigDao.create(appConfigEntity);
            create.setMessage(I18n.getMessage("success.ftpConfigSaved"));
        } catch (Throwable t) {
            create = new Create();
            create.setSuccess(false);
            create.setMessage(I18n.getMessage("error.ftpConfigPortInNotANumber"));
        }
    } 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:com.sos.hibernate.classes.SosHibernateSession.java

License:Apache License

public static Session getInstance(IHibernateOptions options) {
    if (session == null) {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        try {/*w  w  w  .j  a  v  a 2s.c  om*/
            Class dailyScheduleDBItem = classLoader.loadClass("com.sos.dailyschedule.db.DailyScheduleDBItem");
            Class schedulerTaskHistoryDBItem = classLoader
                    .loadClass("com.sos.scheduler.history.db.SchedulerTaskHistoryDBItem");
            Class schedulerOrderStepHistoryDBItem = classLoader
                    .loadClass("com.sos.scheduler.history.db.SchedulerOrderStepHistoryDBItem");
            Class schedulerOrderHistoryDBItem = classLoader
                    .loadClass("com.sos.scheduler.history.db.SchedulerOrderHistoryDBItem");
            Class schedulerInstancesDBItem = classLoader
                    .loadClass("com.sos.scheduler.db.SchedulerInstancesDBItem");
            Class schedulerEventDBItem = classLoader.loadClass("com.sos.eventing.db.SchedulerEventDBItem");

            Class jobNetPlanDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetPlanDBItem");
            Class jobNetNodeDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetNodeDBItem");
            Class jobNetEdgesDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetEdgesDBItem");

            Class eventsDBItem = classLoader.loadClass("com.sos.Jobnet.db.EventsDBItem");

            Class jobNetHistoryDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetHistoryDBItem");
            Class jobNetCmdHistoryDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetCmdHistoryDBItem");
            Class jobNetDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetDBItem");

            // Configuration configuration = new Configuration();
            Configuration configuration = new Configuration().addAnnotatedClass(dailyScheduleDBItem)
                    .addAnnotatedClass(schedulerTaskHistoryDBItem)
                    .addAnnotatedClass(schedulerOrderStepHistoryDBItem)
                    .addAnnotatedClass(schedulerOrderHistoryDBItem).addAnnotatedClass(schedulerInstancesDBItem)
                    .addAnnotatedClass(jobNetPlanDBItem).addAnnotatedClass(jobNetNodeDBItem)
                    .addAnnotatedClass(jobNetEdgesDBItem).addAnnotatedClass(schedulerEventDBItem);
            configuration.setProperty("hibernate.connection.url",
                    options.gethibernate_connection_url().Value());
            configuration.setProperty("hibernate.connection.password",
                    options.gethibernate_connection_password().Value());
            configuration.setProperty("hibernate.connection.url",
                    options.gethibernate_connection_url().Value());
            configuration.setProperty("hibernate.connection.username",
                    options.gethibernate_connection_username().Value());
            configuration.setProperty("hibernate.dialect", options.gethibernate_dialect().Value());
            configuration.setProperty("hibernate.show_sql", options.gethibernate_show_sql().Value());
            configuration.setProperty("hibernate.connection.autocommit",
                    options.gethibernate_connection_autocommit().Value());
            configuration.setProperty("hibernate.format_sql", options.gethibernate_format_sql().Value());
            sessionFactory = configuration.buildSessionFactory();
            session = sessionFactory.openSession();
            session.setFlushMode(FlushMode.ALWAYS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        session.clear();
    }
    return session;
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

License:Apache License

private void initializeHibernate(String driver, String user, String password, String url, String dialect,
        int maxCons, int maxIdleCons, String validationQuery, String mappingFile, String createSchema) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    Configuration config = new Configuration();
    config.setProperty("hibernate.connection.driver_class", driver);
    config.setProperty("hibernate.connection.password", password);
    config.setProperty("hibernate.connection.url", url);
    config.setProperty("hibernate.connection.username", user);
    config.setProperty("hibernate.dialect", dialect);

    if (createSchema == null || createSchema.equalsIgnoreCase("true")) {
        config.setProperty("hibernate.hbm2ddl.auto", "update");
    }/* w  ww.j  a  va2  s .  c  om*/

    config.setProperty("show_sql", "true");
    config.setProperty("hibernate.current_session_context_class", "thread");

    config.setProperty("hibernate.c3p0.max_size", Integer.toString(maxCons));
    config.setProperty("hibernate.c3p0.maxIdleTimeExcessConnections", Integer.toString(maxIdleCons));

    if (validationQuery != null && !validationQuery.isEmpty()) {
        config.setProperty("hibernate.c3p0.testConnectionOnCheckout", "true");
    }
    config.setProperty("hibernate.c3p0.autoCommitOnClose", "true");

    //config.setProperty("hibernate.c3p0.debugUnreturnedConnectionStackTraces", "true");
    //config.setProperty("hibernate.c3p0.unreturnedConnectionTimeout", "30");

    if (validationQuery == null) {
        validationQuery = "SELECT 1";
    }
    config.setProperty("hibernate.c3p0.preferredTestQuery", validationQuery);

    LoadedConfig lc = null;

    if (mappingFile == null || mappingFile.trim().isEmpty()) {
        JaxbCfgHibernateConfiguration jaxbCfg = new JaxbCfgHibernateConfiguration();
        jaxbCfg.setSessionFactory(new JaxbCfgSessionFactory());

        JaxbCfgMappingReferenceType mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(OIDCSession.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        lc = LoadedConfig.consume(jaxbCfg);
    } else {
        lc = LoadedConfig.baseline();
    }

    StandardServiceRegistry registry = builder.configure(lc).applySettings(config.getProperties()).build();
    try {
        if (mappingFile == null || mappingFile.trim().isEmpty()) {
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        } else {
            sessionFactory = new MetadataSources(registry).addResource(mappingFile).buildMetadata()
                    .buildSessionFactory();
        }

        GlobalEntries.getGlobalEntries().getConfigManager().addThread(new StopableThread() {

            @Override
            public void run() {

            }

            @Override
            public void stop() {
                logger.info("Stopping hibernate");
                sessionFactory.close();

            }

        });
    } catch (Exception e) {
        e.printStackTrace();
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy(registry);
    }
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

License:Apache License

private void initializeHibernate(ApprovalDBType adbt) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    Configuration config = new Configuration();
    config.setProperty("hibernate.connection.driver_class", adbt.getDriver());
    config.setProperty("hibernate.connection.password", adbt.getPassword());
    config.setProperty("hibernate.connection.url", adbt.getUrl());
    config.setProperty("hibernate.connection.username", adbt.getUser());
    config.setProperty("hibernate.dialect", adbt.getHibernateDialect());

    if (adbt.isHibernateCreateSchema() == null || adbt.isHibernateCreateSchema()) {
        config.setProperty("hibernate.hbm2ddl.auto", "update");
    }/*from  w  w  w .j  a  va 2s  .co  m*/
    config.setProperty("show_sql", "true");
    config.setProperty("hibernate.current_session_context_class", "thread");

    config.setProperty("hibernate.c3p0.max_size", Integer.toString(adbt.getMaxConns()));
    config.setProperty("hibernate.c3p0.maxIdleTimeExcessConnections", Integer.toString(adbt.getMaxIdleConns()));

    if (adbt.getValidationQuery() != null && !adbt.getValidationQuery().isEmpty()) {
        config.setProperty("hibernate.c3p0.testConnectionOnCheckout", "true");
    }
    config.setProperty("hibernate.c3p0.autoCommitOnClose", "true");

    if (adbt.getHibernateProperty() != null) {
        for (ParamType pt : adbt.getHibernateProperty()) {
            config.setProperty(pt.getName(), pt.getValue());
        }
    }

    //config.setProperty("hibernate.c3p0.debugUnreturnedConnectionStackTraces", "true");
    //config.setProperty("hibernate.c3p0.unreturnedConnectionTimeout", "30");

    String validationQuery = adbt.getValidationQuery();
    if (validationQuery == null) {
        validationQuery = "SELECT 1";
    }
    config.setProperty("hibernate.c3p0.preferredTestQuery", validationQuery);

    LoadedConfig lc = null;

    if (adbt.getHibernateConfig() == null || adbt.getHibernateConfig().trim().isEmpty()) {
        JaxbCfgHibernateConfiguration jaxbCfg = new JaxbCfgHibernateConfiguration();
        jaxbCfg.setSessionFactory(new JaxbCfgSessionFactory());

        JaxbCfgMappingReferenceType mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(AllowedApprovers.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Approvals.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(ApproverAttributes.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Approvers.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(AuditLogs.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(AuditLogType.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Escalation.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Targets.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(UserAttributes.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Users.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(WorkflowParameters.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Workflows.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        lc = LoadedConfig.consume(jaxbCfg);
    } else {
        lc = LoadedConfig.baseline();
    }

    StandardServiceRegistry registry = builder.configure(lc).applySettings(config.getProperties()).build();
    try {
        sessionFactory = null;

        if (adbt.getHibernateConfig() == null || adbt.getHibernateConfig().trim().isEmpty()) {
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        } else {

            sessionFactory = new MetadataSources(registry).addResource(adbt.getHibernateConfig())
                    .buildMetadata().buildSessionFactory();
        }

        this.cfgMgr.addThread(new StopableThread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

            }

            @Override
            public void stop() {
                logger.info("Stopping hibernate");
                sessionFactory.close();

            }

        });

        org.hibernate.Session session = sessionFactory.openSession();

        this.auditLogTypes = new HashMap<String, AuditLogType>();

        List<AuditLogType> alts = session.createCriteria(AuditLogType.class).list();
        if (alts.size() == 0) {
            session.beginTransaction();
            AuditLogType alt = new AuditLogType();
            alt.setName("Add");
            session.save(alt);

            this.auditLogTypes.put("add", alt);

            alt = new AuditLogType();
            alt.setName("Delete");
            session.save(alt);

            this.auditLogTypes.put("delete", alt);

            alt = new AuditLogType();
            alt.setName("Replace");
            session.save(alt);

            this.auditLogTypes.put("replace", alt);

            session.getTransaction().commit();
        } else {
            for (AuditLogType alt : alts) {
                this.auditLogTypes.put(alt.getName().toLowerCase(), alt);
            }
        }

        session.close();

    } catch (Exception e) {
        e.printStackTrace();
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy(registry);
    }
}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

License:Apache License

private void initializeHibernate(String driver, String user, String password, String url, String dialect,
        int maxCons, int maxIdleCons, String validationQuery, String mappingFile, String createSchema) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    Configuration config = new Configuration();
    config.setProperty("hibernate.connection.driver_class", driver);
    config.setProperty("hibernate.connection.password", password);
    config.setProperty("hibernate.connection.url", url);
    config.setProperty("hibernate.connection.username", user);
    config.setProperty("hibernate.dialect", dialect);

    if (createSchema == null || createSchema.equalsIgnoreCase("true")) {
        config.setProperty("hibernate.hbm2ddl.auto", "update");
    }//from w  w  w.j  ava2s  .  com

    config.setProperty("show_sql", "true");
    config.setProperty("hibernate.current_session_context_class", "thread");

    config.setProperty("hibernate.c3p0.max_size", Integer.toString(maxCons));
    config.setProperty("hibernate.c3p0.maxIdleTimeExcessConnections", Integer.toString(maxIdleCons));

    if (validationQuery != null && !validationQuery.isEmpty()) {
        config.setProperty("hibernate.c3p0.testConnectionOnCheckout", "true");
    }

    config.setProperty("hibernate.c3p0.autoCommitOnClose", "true");

    //config.setProperty("hibernate.c3p0.debugUnreturnedConnectionStackTraces", "true");
    //config.setProperty("hibernate.c3p0.unreturnedConnectionTimeout", "30");

    if (validationQuery == null) {
        validationQuery = "SELECT 1";
    }
    config.setProperty("hibernate.c3p0.preferredTestQuery", validationQuery);

    LoadedConfig lc = null;

    if (mappingFile == null || mappingFile.trim().isEmpty()) {

        JaxbCfgHibernateConfiguration jaxbCfg = new JaxbCfgHibernateConfiguration();
        jaxbCfg.setSessionFactory(new JaxbCfgSessionFactory());

        JaxbCfgMappingReferenceType mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(PasswordResetRequest.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);

        lc = LoadedConfig.consume(jaxbCfg);
    } else {
        lc = LoadedConfig.baseline();
    }

    StandardServiceRegistry registry = builder.configure(lc).applySettings(config.getProperties()).build();
    try {
        sessionFactory = null;

        if (mappingFile == null || mappingFile.trim().isEmpty()) {
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        } else {
            sessionFactory = new MetadataSources(registry).addResource(mappingFile).buildMetadata()
                    .buildSessionFactory();
        }

        this.cfgMgr.addThread(new StopableThread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

            }

            @Override
            public void stop() {
                logger.info("Stopping hibernate");
                sessionFactory.close();

            }

        });
    } catch (Exception e) {
        e.printStackTrace();
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy(registry);
    }
}