Java Code Examples for org.hibernate.cfg.Configuration

The following are top voted examples for showing how to use org.hibernate.cfg.Configuration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: java-jdbc   File: HibernateTest.java   View source code 7 votes vote down vote up
private SessionFactory createSessionFactory(boolean traceWithActiveSpanOnly) {
  Configuration configuration = new Configuration();
  configuration.addAnnotatedClass(Employee.class);
  configuration.setProperty("hibernate.connection.driver_class",
      "io.opentracing.contrib.jdbc.TracingDriver");
  configuration.setProperty("hibernate.connection.url",
      "jdbc:tracing:h2:mem:hibernate?traceWithActiveSpanOnly=" + traceWithActiveSpanOnly);
  configuration.setProperty("hibernate.connection.username", "sa");
  configuration.setProperty("hibernate.connection.password", "");
  configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
  configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
  configuration.setProperty("hibernate.show_sql", "true");
  configuration.setProperty("hibernate.connection.pool_size", "10");

  StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
      .applySettings(configuration.getProperties());
  return configuration.buildSessionFactory(builder.build());
}
 
Example 2
Project: java-p6spy   File: HibernateTest.java   View source code 6 votes vote down vote up
private SessionFactory createSessionFactory(String options) {
  Configuration configuration = new Configuration();
  configuration.addAnnotatedClass(Employee.class);
  configuration.setProperty("hibernate.connection.url", "jdbc:p6spy:hsqldb:mem:hibernate" + options);
  configuration.setProperty("hibernate.connection.username", "sa");
  configuration.setProperty("hibernate.connection.password", "");
  configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
  configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
  configuration.setProperty("hibernate.show_sql", "true");
  configuration.setProperty("hibernate.connection.pool_size", "10");

  StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
      .applySettings(configuration.getProperties());
  SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
  return sessionFactory;
}
 
Example 3
Project: Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update   File: TestClass.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Configuration cfg=null;
	SessionFactory factory=null;
	Session ses=null;
	Transaction tx=null;
			cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
			factory=cfg.buildSessionFactory();
		ses=factory.openSession();
	
		 String hql="select item_name from bigbazarModel where bazarid=:id";
		 Query q=ses.createQuery(hql);
		 		q.setParameter("id", 1001);
		 			String s=(String) q.uniqueResult();
		 			System.out.println("\t\t"+s);
		 			
		 			factory.close();

}
 
Example 4
Project: Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update   File: copy_HQL.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
	Configuration cfg=null;
	SessionFactory factory=null;
	Session ses=null;
	 Transaction tx=null;
			cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
			factory=cfg.buildSessionFactory();
		ses=factory.openSession();
	
		tx=ses.beginTransaction();
		 String hql="insert into newMall(mallid,item_name,item_price,item_quantity) "
		 			+ "select bazarid,item_name,item_price,item_quantity from bigbazarModel ";
		 Query q=ses.createQuery(hql);
		 			int c=q.executeUpdate();
		 			//int count=Integer.parseUnsignedInt(c);
		 			tx.commit();
		 			System.out.println("\t\t"+c+" rows Copied Successfully...");
		 		
		 			factory.close();

}
 
Example 5
Project: otus_java_2017_06   File: DBServiceImpl.java   View source code 6 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(UserDataSet.class);
    configuration.addAnnotatedClass(PhoneDataSet.class);

    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example");
    configuration.setProperty("hibernate.connection.username", "tully");
    configuration.setProperty("hibernate.connection.password", "tully");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.connection.useSSL", "false");
    configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true");
    configuration.setProperty("hibernate.jdbc.time_zone", "UTC");

    sessionFactory = createSessionFactory(configuration);
}
 
Example 6
Project: otus_java_2017_06   File: DBServiceImpl.java   View source code 6 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(UserDataSet.class);
    configuration.addAnnotatedClass(PhoneDataSet.class);
    configuration.addAnnotatedClass(AddressDataSet.class);

    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example");
    configuration.setProperty("hibernate.connection.username", "tully");
    configuration.setProperty("hibernate.connection.password", "tully");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.connection.useSSL", "false");
    configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true");

    sessionFactory = createSessionFactory(configuration);
}
 
Example 7
Project: dhus-core   File: EntityCallbackHandlerInitializer.java   View source code 6 votes vote down vote up
@PostConstruct
public void init() throws ClassNotFoundException
{
  final Configuration configuration = annotationSessionFactory
        .getConfiguration();
  final ReflectionManager reflectionManager = configuration
        .getReflectionManager();
  final Iterator<PersistentClass> classMappings = configuration
        .getClassMappings();
  while (classMappings.hasNext()) 
  {
     entityCallbackHandler.add(reflectionManager.classForName(
        classMappings.next().getClassName(), this.getClass()),
        reflectionManager);
  }
}
 
Example 8
Project: otus_java_2017_04   File: DBServiceImpl.java   View source code 6 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(UserDataSet.class);
    configuration.addAnnotatedClass(PhoneDataSet.class);

    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example");
    configuration.setProperty("hibernate.connection.username", "tully");
    configuration.setProperty("hibernate.connection.password", "tully");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.connection.useSSL", "false");
    configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true");

    sessionFactory = createSessionFactory(configuration);
}
 
Example 9
Project: Celebino   File: HibernateUtil.java   View source code 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
	try {

		logger.info("Configurando conexao Hibernate->MySQL");
		Configuration configuration = new Configuration().configure();

		logger.info("Hibernate->MySQL - Properties: " + configuration.getProperties());

		// Create the SessionFactory from hibernate.cfg.xml
		return configuration.buildSessionFactory();

	} catch (Throwable ex) {
		// Make sure you log the exception, as it might be swallowed
		logger.error("Initial SessionFactory creation failed." + ex);
		throw new ExceptionInInitializerError(ex);
	}
}
 
Example 10
Project: Hotel-Properties-Management-System   File: DataSourceFactory.java   View source code 6 votes vote down vote up
public static synchronized void createConnection() {
	try {

		if (sessionFactory == null) {
			sessionFactory = new Configuration().configure("com/coder/hms/connection/hibernate.cfg.xml")
					.addAnnotatedClass(Reservation.class).buildSessionFactory();
		}

	} catch (HibernateException e) {
		Toolkit.getDefaultToolkit().beep();
		final InformationFrame dialog = new InformationFrame();
		dialog.setMessage("Sorry we can't connect to database right now, without "
				+ "connection the application will not work properly.");
		dialog.okBtn.addActionListener(ActionListener->{
			return;
		});
		dialog.setVisible(true);
	}
}
 
Example 11
Project: OpenVertretung   File: HibernateFabric.java   View source code 6 votes vote down vote up
/**
 * Configuration of session factory with Fabric integration.
 */
public static SessionFactory createSessionFactory(String fabricUrl, String username, String password, String fabricUser, String fabricPassword)
        throws Exception {
    // creating this here allows passing needed params to the constructor
    FabricMultiTenantConnectionProvider connProvider = new FabricMultiTenantConnectionProvider(fabricUrl, "employees", "employees", username, password,
            fabricUser, fabricPassword);
    ServiceRegistryBuilder srb = new ServiceRegistryBuilder();
    srb.addService(org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider.class, connProvider);
    srb.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

    Configuration config = new Configuration();
    config.setProperty("hibernate.multiTenancy", "DATABASE");
    config.addResource("com/mysql/fabric/demo/employee.hbm.xml");
    return config.buildSessionFactory(srb.buildServiceRegistry());
}
 
Example 12
Project: otus_java_2017_10   File: DbService.java   View source code 6 votes vote down vote up
public DbService() {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(UserDataSet.class);
    configuration.addAnnotatedClass(AddressDataSet.class);
    configuration.addAnnotatedClass(PhoneDataSet.class);
    configuration.addAnnotatedClass(Account.class);

    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:h2:~/test");
    configuration.setProperty("hibernate.connection.username", "sa");
    configuration.setProperty("hibernate.connection.password", "");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.connection.useSSL", "false");
    configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true");

    sessionFactory = createSessionFactory(configuration);
}
 
Example 13
Project: lams   File: SchemaExport.java   View source code 6 votes vote down vote up
public SchemaExport(ServiceRegistry serviceRegistry, Configuration configuration) {
	this.connectionHelper = new SuppliedConnectionProviderConnectionHelper(
			serviceRegistry.getService( ConnectionProvider.class )
	);
	this.sqlStatementLogger = serviceRegistry.getService( JdbcServices.class ).getSqlStatementLogger();
	this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
	this.sqlExceptionHelper = serviceRegistry.getService( JdbcServices.class ).getSqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			configuration.getProperties(),
			DEFAULT_IMPORT_FILE
	);

	final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect();
	this.dropSQL = configuration.generateDropSchemaScript( dialect );
	this.createSQL = configuration.generateSchemaCreationScript( dialect );
}
 
Example 14
Project: lams   File: SchemaUpdateTask.java   View source code 6 votes vote down vote up
private SchemaUpdate getSchemaUpdate(Configuration cfg) throws HibernateException, IOException {
	Properties properties = new Properties();
	properties.putAll( cfg.getProperties() );
	if (propertiesFile == null) {
		properties.putAll( getProject().getProperties() );
	}
	else {
		properties.load( new FileInputStream(propertiesFile) );
	}
	cfg.setProperties(properties);
	SchemaUpdate su = new SchemaUpdate(cfg);
	su.setOutputFile( outputFile.getPath() );
	su.setDelimiter(delimiter);
	su.setHaltOnError(haltOnError);
	return su;
}
 
Example 15
Project: lams   File: SessionFactoryServiceRegistryImpl.java   View source code 6 votes vote down vote up
@SuppressWarnings( {"unchecked"})
public SessionFactoryServiceRegistryImpl(
		ServiceRegistryImplementor parent,
		SessionFactoryImplementor sessionFactory,
		Configuration configuration) {
	super( parent );

	this.sessionFactory = sessionFactory;
	this.configuration = configuration;
	this.metadata = null;

	// for now, just use the standard initiator list
	for ( SessionFactoryServiceInitiator initiator : StandardSessionFactoryServiceInitiators.LIST ) {
		// create the bindings up front to help identify to which registry services belong
		createServiceBinding( initiator );
	}
}
 
Example 16
Project: Transwarp-Sample-Code   File: InHibernate.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    String path = "hibernate.cfg.xml";
    Configuration cfg = new Configuration().configure(path);

    SessionFactory sessionFactory = cfg.buildSessionFactory();

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    User user = new User();
    user.setId("443");
    user.setName("baa");
    session.save(user);
    // session.close();
    session.getTransaction().commit();
    sessionFactory.close();
}
 
Example 17
Project: Transwarp-Sample-Code   File: InHibernate.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    String path = "hibernate.cfg.xml";
    Configuration cfg = new Configuration().configure(path);

    SessionFactory sessionFactory = cfg.buildSessionFactory();

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    User user = new User();
    user.setId("46");
    user.setName("aaa");
    session.save(user);
    // session.close();
    session.getTransaction().commit();
    sessionFactory.close();
}
 
Example 18
Project: Transwarp-Sample-Code   File: InHibernate.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    String path = "hibernate.cfg.xml";
    Configuration cfg = new Configuration().configure(path);

    SessionFactory sessionFactory = cfg.buildSessionFactory();

    Session session = sessionFactory.openSession();
    session.beginTransaction();
    User user = new User();
    user.setId("443");
    user.setName("baa");
    session.save(user);
    // session.close();
    session.getTransaction().commit();
    sessionFactory.close();
}
 
Example 19
Project: otus_java_2017_10   File: DBServiceImpl.java   View source code 6 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(UserDataSet.class);
    configuration.addAnnotatedClass(PhoneDataSet.class);
    configuration.addAnnotatedClass(EmptyDataSet.class);

    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example");
    configuration.setProperty("hibernate.connection.username", "tully");
    configuration.setProperty("hibernate.connection.password", "tully");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.connection.useSSL", "false");
    configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true");

    sessionFactory = createSessionFactory(configuration);
}
 
Example 20
Project: userinterface   File: HibernateUtil.java   View source code 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
        if (sessionFactory == null || sessionFactory.isClosed()) {
            try {
                Configuration configuration = new Configuration().configure();
                StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
                serviceRegistryBuilder.applySettings(configuration.getProperties());
                ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
//            sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (HibernateException ex) {
                ex.printStackTrace();
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
        return sessionFactory;
    }
 
Example 21
Project: otus_java_2017_04   File: DBServiceImpl.java   View source code 6 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(UserDataSet.class);
    configuration.addAnnotatedClass(PhoneDataSet.class);
    configuration.addAnnotatedClass(AddressDataSet.class);

    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/db_example");
    configuration.setProperty("hibernate.connection.username", "tully");
    configuration.setProperty("hibernate.connection.password", "tully");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.setProperty("hibernate.connection.useSSL", "false");
    configuration.setProperty("hibernate.enable_lazy_load_no_trans", "true");

    sessionFactory = createSessionFactory(configuration);
}
 
Example 22
Project: unitimes   File: HibernateUtil.java   View source code 6 votes vote down vote up
public static void fixSchemaInFormulas(Configuration cfg) {
	cfg.buildMappings();
    String schema = cfg.getProperty("default_schema"); 
    if (schema!=null) {
        for (Iterator i=cfg.getClassMappings();i.hasNext();) {
            PersistentClass pc = (PersistentClass)i.next();
            for (Iterator j=pc.getPropertyIterator();j.hasNext();) {
                Property p = (Property)j.next();
                for (Iterator k=p.getColumnIterator();k.hasNext();) {
                    Selectable c = (Selectable)k.next();
                    if (c instanceof Formula) {
                        Formula f = (Formula)c;
                        if (f.getFormula()!=null && f.getFormula().indexOf("%SCHEMA%")>=0) {
                            f.setFormula(f.getFormula().replaceAll("%SCHEMA%", schema));
                            sLog.debug("Schema updated in "+pc.getClassName()+"."+p.getName()+" to "+f.getFormula());
                        }
                    }
                }
            }
        }
    }
}
 
Example 23
Project: docker-restful-java   File: HibernateUtil.java   View source code 5 votes vote down vote up
/**
 * Create the SessionFactory from hibernate.cfg.xml
 *
 * @return A new SessionFactory
 */
private static SessionFactory buildSessionFactory() {
    try {
        return new Configuration().configure().buildSessionFactory();
    } catch (Throwable exception) {
        System.err.println("Initial SessionFactory creation failed." + exception);
        throw new ExceptionInInitializerError(exception);
    }
}
 
Example 24
Project: otus_java_2017_04   File: DBServiceImpl.java   View source code 5 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration()
            .configure(new File("config/hibernate.cfg.xml"))
            .addFile(new File("config/UserDataSet.hbm.xml"));

    sessionFactory = createSessionFactory(configuration);
}
 
Example 25
Project: alfresco-repository   File: ScriptExecutorImpl.java   View source code 5 votes vote down vote up
@Override
public void executeScriptUrl(String scriptUrl) throws Exception
{
    Configuration cfg = localSessionFactory.getConfiguration();
    Connection connection = dataSource.getConnection();
    connection.setAutoCommit(true);
    try
    {
        executeScriptUrl(cfg, connection, scriptUrl);
    }
    finally
    {
        connection.close();
    }
}
 
Example 26
Project: alfresco-repository   File: ScriptExecutorImpl.java   View source code 5 votes vote down vote up
private void executeScriptUrl(Configuration cfg, Connection connection, String scriptUrl) throws Exception
{
    Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getSimpleName();
    InputStream scriptInputStream = getScriptInputStream(dialect.getClass(), scriptUrl);
    // check that it exists
    if (scriptInputStream == null)
    {
        throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_FOUND, scriptUrl);
    }
    // write the script to a temp location for future and failure reference
    File tempFile = null;
    try
    {
        tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
        ContentWriter writer = new FileContentWriter(tempFile);
        writer.putContent(scriptInputStream);
    }
    finally
    {
        try { scriptInputStream.close(); } catch (Throwable e) {}  // usually a duplicate close
    }
    // now execute it
    String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_DIALECT, dialect.getClass().getName());
    // Replace the script placeholders
    executeScriptFile(cfg, connection, tempFile, dialectScriptUrl);
}
 
Example 27
Project: alfresco-repository   File: SchemaBootstrap.java   View source code 5 votes vote down vote up
private void executeScriptUrl(Configuration cfg, Connection connection, String scriptUrl) throws Exception
{
    Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getSimpleName();
    InputStream scriptInputStream = getScriptInputStream(dialect.getClass(), scriptUrl);
    // check that it exists
    if (scriptInputStream == null)
    {
        throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_FOUND, scriptUrl);
    }
    // write the script to a temp location for future and failure reference
    File tempFile = null;
    try
    {
        tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
        ContentWriter writer = new FileContentWriter(tempFile);
        writer.putContent(scriptInputStream);
    }
    finally
    {
        try { scriptInputStream.close(); } catch (Throwable e) {}  // usually a duplicate close
    }
    // now execute it
    String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_DIALECT, dialect.getClass().getName());
    // Replace the script placeholders
    executeScriptFile(cfg, connection, tempFile, dialectScriptUrl);
}
 
Example 28
Project: alfresco-core   File: DialectFactoryBean.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Dialect getObject() throws SQLException
{
    Session session = ((SessionFactory) this.localSessionFactory.getObject()).openSession();
    Configuration cfg = this.localSessionFactory.getConfiguration();
    Connection con = null;
    try
    {
        // make sure that we AUTO-COMMIT
        con = session.connection();
        con.setAutoCommit(true);
        DatabaseMetaData meta = con.getMetaData();

        overrideDialectPropertyForDriver(cfg.getProperties(), meta.getDriverName());

        Dialect dialect = DialectFactory.buildDialect(cfg.getProperties(), meta.getDatabaseProductName(), meta.getDatabaseMajorVersion());

        dialect = changeDialect(cfg, dialect);
        return dialect;
    }
    finally
    {
        try
        {
            con.close();
        }
        catch (Exception e)
        {
        }
    }
}
 
Example 29
Project: alfresco-core   File: DialectFactoryBean.java   View source code 5 votes vote down vote up
/**
 * Substitute the dialect with an alternative, if possible.
 * 
 * @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.alfresco.com/jira/browse/ETHREEOH-679
    // else if (dialectName.equals(Oracle9Dialect.class.getName()))
    // {
    // String subst = AlfrescoOracle9Dialect.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);
    // }
}
 
Example 30
Project: otus_java_2017_06   File: DBServiceImpl.java   View source code 5 votes vote down vote up
public DBServiceImpl() {
    Configuration configuration = new Configuration()
            .configure(new File("config/hibernate.cfg.xml"))
            .addFile(new File("config/UserDataSet.hbm.xml"));

    sessionFactory = createSessionFactory(configuration);
}
 
Example 31
Project: excel-util4j   File: TestImportHandlerForCascadePojo.java   View source code 5 votes vote down vote up
@Before
public void init() {

    // 准备环境
    {
        Configuration configuration = new Configuration().configure("hbm.cfg.xml");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        factory = configuration.buildSessionFactory(serviceRegistry);
    }
}
 
Example 32
Project: the-vigilantes   File: HibernateFabric.java   View source code 5 votes vote down vote up
/**
 * Configuration of session factory with Fabric integration.
 */
public static SessionFactory createSessionFactory(String fabricUrl, String username, String password, String fabricUser, String fabricPassword)
        throws Exception {
    // creating this here allows passing needed params to the constructor
    FabricMultiTenantConnectionProvider connProvider = new FabricMultiTenantConnectionProvider(fabricUrl, "employees", "employees", username, password,
            fabricUser, fabricPassword);
    ServiceRegistryBuilder srb = new ServiceRegistryBuilder();
    srb.addService(org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider.class, connProvider);
    srb.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

    Configuration config = new Configuration();
    config.setProperty("hibernate.multiTenancy", "DATABASE");
    config.addResource("com/mysql/fabric/demo/employee.hbm.xml");
    return config.buildSessionFactory(srb.buildServiceRegistry());
}
 
Example 33
Project: OSWf-OSWorkflow-fork   File: StartupContextListener.java   View source code 5 votes vote down vote up
private SessionFactory createSessionFactory() {
    
    SessionFactory sessionFactory = null;

    try {

        String resource;
        
        Configuration configuration = new Configuration();

        resource = "oswf-store.cfg.xml";
        logger.info("Configuring Hibernate Mapping: " + resource);
        configuration.configure(resource);
      
        // Database configuration; H2 or MySQL
        resource = "hibernate.xml";
        logger.info("Configuring Hibernate Mapping: " + resource);
        configuration.configure(resource);
        
        // Attempt to create the SessionFactory; exceptions may be thrown                
        sessionFactory =  configuration.buildSessionFactory();

    } catch (Throwable e) {
        logger.error(fatal, "Failed to create Hibernate SessionFactory: " + e.toString());
        sessionFactory = null;
    }
    
    return sessionFactory;
}
 
Example 34
Project: BibliotecaPS   File: HibernateFabric.java   View source code 5 votes vote down vote up
/**
 * Configuration of session factory with Fabric integration.
 */
public static SessionFactory createSessionFactory(String fabricUrl, String username, String password, String fabricUser, String fabricPassword)
        throws Exception {
    // creating this here allows passing needed params to the constructor
    FabricMultiTenantConnectionProvider connProvider = new FabricMultiTenantConnectionProvider(fabricUrl, "employees", "employees", username, password,
            fabricUser, fabricPassword);
    ServiceRegistryBuilder srb = new ServiceRegistryBuilder();
    srb.addService(org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider.class, connProvider);
    srb.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

    Configuration config = new Configuration();
    config.setProperty("hibernate.multiTenancy", "DATABASE");
    config.addResource("com/mysql/fabric/demo/employee.hbm.xml");
    return config.buildSessionFactory(srb.buildServiceRegistry());
}
 
Example 35
Project: FH-Manager   File: SessionFactory.java   View source code 5 votes vote down vote up
private SessionFactory() {
    try {
        HibernateConfiguration hibernateConfiguration = ConfigurationWrapper.getInstance().getHibernateConfiguration();
        Configuration configuration = new Configuration();
        initHBMs(configuration);
        configuration.configure(hibernateConfiguration.getPathToConfigurationFile());
        StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(standardServiceRegistryBuilder.build());
    }catch (Exception excetption){

    }
}
 
Example 36
Project: FH-Manager   File: SessionFactory.java   View source code 5 votes vote down vote up
private void initHBMs(Configuration configuration) throws IOException {
    //TODO test this.
    Enumeration<URL> resources = getClass().getClassLoader().getResources("");
    while(resources.hasMoreElements()){
        URL url = resources.nextElement();
        String file = url.getFile();
        if(file.endsWith(".hbm.xml")){
            configuration.addResource(file);
        }
    }
}
 
Example 37
Project: lams   File: LocalSessionFactoryBean.java   View source code 5 votes vote down vote up
/**
 * Return the Hibernate Configuration object used to build the SessionFactory.
 * Allows for access to configuration metadata stored there (rarely needed).
 * @throws IllegalStateException if the Configuration object has not been initialized yet
 */
public final Configuration getConfiguration() {
	if (this.configuration == null) {
		throw new IllegalStateException("Configuration not initialized yet");
	}
	return this.configuration;
}
 
Example 38
Project: lams   File: AnnotationSessionFactoryBean.java   View source code 5 votes vote down vote up
/**
 * Reads metadata from annotated classes and packages into the
 * AnnotationConfiguration instance.
 */
@Override
protected void postProcessMappings(Configuration config) throws HibernateException {
	if (this.annotatedClasses != null) {
		for (Class<?> annotatedClass : this.annotatedClasses) {
			config.addAnnotatedClass(annotatedClass);
		}
	}
	if (this.annotatedPackages != null) {
		for (String annotatedPackage : this.annotatedPackages) {
			config.addPackage(annotatedPackage);
		}
	}
	scanPackages(config);
}
 
Example 39
Project: lams   File: LocalSessionFactoryBean.java   View source code 5 votes vote down vote up
/**
 * Specify the Hibernate Configuration class to use.
 * <p>Default is {@link org.hibernate.cfg.Configuration}; any subclass
 * of this default Hibernate Configuration class can be specified.
 */
@SuppressWarnings("unchecked")
public void setConfigurationClass(Class<?> configurationClass) {
	if (configurationClass == null || !Configuration.class.isAssignableFrom(configurationClass)) {
		throw new IllegalArgumentException(
				"'configurationClass' must be assignable to [org.hibernate.cfg.Configuration]");
	}
	this.configurationClass = (Class<? extends Configuration>) configurationClass;
}
 
Example 40
Project: lams   File: LocalSessionFactoryBean.java   View source code 5 votes vote down vote up
/**
 * Return the Configuration object used to build the SessionFactory.
 * Allows for access to configuration metadata stored there (rarely needed).
 * @throws IllegalStateException if the Configuration object has not been initialized yet
 */
public final Configuration getConfiguration() {
	if (this.configuration == null) {
		throw new IllegalStateException("Configuration not initialized yet");
	}
	return this.configuration;
}