Example usage for org.hibernate.cfg Configuration buildMappings

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

Introduction

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

Prototype

@Deprecated
public void buildMappings() 

Source Link

Usage

From source file:com.blazebit.persistence.integration.hibernate.Hibernate43Integrator.java

License:Apache License

@Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {
    Class<?> valuesEntity;//w ww  .j a  v a 2 s  . c o m
    boolean registerValuesEntity = true;
    try {
        valuesEntity = Class.forName("com.blazebit.persistence.impl.function.entity.ValuesEntity");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Are you missing blaze-persistence-core-impl on the classpath?", e);
    }

    Iterator<PersistentClass> iter = configuration.getClassMappings();
    while (iter.hasNext()) {
        PersistentClass clazz = iter.next();
        Class<?> entityClass = clazz.getMappedClass();

        if (entityClass != null && entityClass.isAnnotationPresent(CTE.class)) {
            clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName());
        }
    }

    if (registerValuesEntity) {
        // Register values entity if wasn't found
        configuration.addAnnotatedClass(valuesEntity);
        configuration.buildMappings();
        PersistentClass clazz = configuration.getClassMapping(valuesEntity.getName());
        clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName());
    }

    serviceRegistry.locateServiceBinding(PersisterClassResolver.class)
            .setService(new CustomPersisterClassResolver());
    serviceRegistry.locateServiceBinding(Database.class)
            .setService(new SimpleDatabase(configuration.getTableMappings(), sessionFactory.getDialect(),
                    new SimpleTableNameFormatter(), configuration.buildMapping()));
}

From source file:com.blazebit.persistence.integration.hibernate.Hibernate4Integrator.java

License:Apache License

@Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {
    Class<?> valuesEntity;//from  ww  w  .  j a v a2 s . c  o  m
    boolean registerValuesEntity = true;
    try {
        valuesEntity = Class.forName("com.blazebit.persistence.impl.function.entity.ValuesEntity");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Are you missing blaze-persistence-core-impl on the classpath?", e);
    }

    Iterator<PersistentClass> iter = configuration.getClassMappings();
    while (iter.hasNext()) {
        PersistentClass clazz = iter.next();
        Class<?> entityClass = clazz.getMappedClass();
        if (valuesEntity.equals(entityClass)) {
            registerValuesEntity = false;
        }

        if (entityClass != null && entityClass.isAnnotationPresent(CTE.class)) {
            clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName());
        }
    }

    if (registerValuesEntity) {
        // Register values entity if wasn't found
        configuration.addAnnotatedClass(valuesEntity);
        configuration.buildMappings();
        PersistentClass clazz = configuration.getClassMapping(valuesEntity.getName());
        clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName());
    }

    serviceRegistry.locateServiceBinding(PersisterClassResolver.class)
            .setService(new CustomPersisterClassResolver());
    serviceRegistry.locateServiceBinding(Database.class)
            .setService(new SimpleDatabase(configuration.getTableMappings(), sessionFactory.getDialect(),
                    new SimpleTableNameFormatter(), configuration.buildMapping()));
}

From source file:com.corundumstudio.core.extensions.hibernate.BaseTest.java

License:Apache License

protected static void initHibernate() {
    Properties props = buildDatabaseConfiguration("db1");

    Configuration cfg = new Configuration();
    cfg.setProperty(Environment.GENERATE_STATISTICS, "true");
    cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "create");
    cfg.setProperty(AvailableSettings.CACHE_REGION_FACTORY, InfinispanRegionFactory.class.getName());
    cfg.setProperty(InfinispanRegionFactory.INFINISPAN_CONFIG_RESOURCE_PROP, "infinispan.xml");
    cfg.setProperty(AvailableSettings.QUERY_CACHE_FACTORY, DynamicQueryCacheFactory.class.getName());
    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
    cfg.addAnnotatedClass(SimpleEntity.class);
    cfg.buildMappings();

    ServiceRegistryBuilder sb = new ServiceRegistryBuilder();
    ServiceRegistry serviceRegistry = sb.applySettings(props).buildServiceRegistry();
    sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory(serviceRegistry);

    EventListenerRegistry registry = sessionFactory.getServiceRegistry()
            .getService(EventListenerRegistry.class);
    registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(queryCacheEntityListener);
    registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(queryCacheEntityListener);
    registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(queryCacheEntityListener);
}

From source file:com.db4o.drs.hibernate.impl.ReplicationConfiguration.java

License:Open Source License

public static Configuration decorate(Configuration c) {
    for (Class cl : Util._metadataClasses)
        Util.addClass(c, cl);//from w w w.  j a v a2 s. com
    c.buildMappings();
    return c;
}

From source file:com.frameworkset.common.poolman.hibernate.LocalSessionFactoryBean.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();

    if (dataSource != null) {
        this.configTimeDataSourceHolder.set(dataSource);
    }// ww w .j ava2s.  c  o m
    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.beanClassLoader != null
            && !this.beanClassLoader.equals(threadContextClassLoader));
    try {
        if (overrideClassLoader) {
            currentThread.setContextClassLoader(this.beanClassLoader);
        }

        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.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                config.configure(resource.getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            Properties temp = new Properties();
            temp.putAll(this.hibernateProperties);
            config.addProperties(temp);
        }

        if (dataSource != null) {
            Class providerClass = LocalDataSourceConnectionProvider.class;

            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                config.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (Resource resource : this.mappingDirectoryLocations) {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException(
                            "Mapping directory location [" + resource + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

        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 = SimpleStringUtil
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    // method signature declares return type as Configuration on Hibernate 3.6
                    // but as void on Hibernate 3.3 and 3.5
                    Method setCacheConcurrencyStrategy = Configuration.class
                            .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class);
                    ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config,
                            new Object[] { 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 = SimpleStringUtil
                        .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<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<Object> listeners = (Collection<Object>) 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.info("Building new Hibernate SessionFactory");
        this.configuration = config;
        return newSessionFactory(config);
    }

    finally {

        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
        configTimeDataSourceHolder.set(null);
    }
}

From source file:com.github.antennaesdk.messageserver.db.H2.H2Database.java

License:Apache License

public void generateSchemaAndCreateTables(SimpleDriverDataSource dataSource) {

    // Get the tables that are already in the DATABASE
    List<String> tables = new ArrayList<>();
    try {//from   w w w .ja va 2s .  c  om
        Connection connection = dataSource.getConnection();
        DatabaseMetaData databaseMetadata = connection.getMetaData();
        ResultSet resultSet = databaseMetadata.getTables(null, null, null, new String[] { "TABLE" });
        while (resultSet.next()) {
            String table = resultSet.getString(3);
            logger.info("Table : " + table + " ... exists");
            tables.add(table);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // Get the tables that are needed from Entity Classes
    List<Class> tablesToCreate = new ArrayList<>();
    for (Class<?> c : entityClasses) {
        // get the table names
        Table table = c.getAnnotation(Table.class);

        logger.info("Entity: " + c.getName() + " , Table: " + table.name());
        boolean isExisting = false;
        for (String dbTable : tables) {
            if (dbTable.equals(table.name())) {
                isExisting = true;
                break;
            }
        }

        if (!isExisting) {
            // these tables must be created
            tablesToCreate.add(c);
        }
    }

    // Check whether the tables need to be created...
    if (tablesToCreate.size() == 0) {
        logger.info("Tables already exist... ");
        return;
    } else {
        logger.info("Creating tables...");
    }

    //create a minimal configuration
    org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration();
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    cfg.setProperty("hibernate.hbm2ddl.auto", "create");

    // create a temporary file to write the DDL
    File ddlFile = null;
    try {
        File dir = getDirectoryFromClasspath();
        ddlFile = File.createTempFile("H2_", ".SQL", dir);
        ddlFile.deleteOnExit();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // add the tables to be created
    for (Class c : tablesToCreate) {
        cfg.addAnnotatedClass(c);
    }

    //build all the mappings, before calling the AuditConfiguration
    cfg.buildMappings();
    cfg.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, ddlFile.getName());

    cfg.getProperties().setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    cfg.getProperties().setProperty("hibernate.connection.url", dataSource.getUrl());
    cfg.getProperties().setProperty("hibernate.connection.username", dataSource.getUsername());
    cfg.getProperties().setProperty("hibernate.connection.password", dataSource.getPassword());

    //execute the export
    SchemaExport export = new SchemaExport(cfg);

    export.setDelimiter(";");
    export.setFormat(true);
    // create the tables in the DB and show the DDL in console
    export.create(true, true);
}

From source file:com.mysema.query.jpa.codegen.HibernateDomainExporter.java

License:Apache License

/**
 * Create a new HibernateDomainExporter instance
 * /*from  w  w  w . j av  a2 s  .co m*/
 * @param namePrefix
 * @param nameSuffix
 * @param targetFolder
 * @param serializerConfig
 * @param configuration
 * @param charset
 */
public HibernateDomainExporter(String namePrefix, String nameSuffix, File targetFolder,
        SerializerConfig serializerConfig, Configuration configuration, Charset charset) {
    this.targetFolder = targetFolder;
    this.serializerConfig = serializerConfig;
    this.configuration = configuration;
    this.charset = charset;
    configuration.buildMappings();
    CodegenModule module = new CodegenModule();
    module.bind(CodegenModule.PREFIX, namePrefix);
    module.bind(CodegenModule.SUFFIX, nameSuffix);
    module.bind(CodegenModule.KEYWORDS, Constants.keywords);
    this.queryTypeFactory = module.get(QueryTypeFactory.class);
    this.typeMappings = module.get(TypeMappings.class);
    this.embeddableSerializer = module.get(EmbeddableSerializer.class);
    this.entitySerializer = module.get(EntitySerializer.class);
    this.supertypeSerializer = module.get(SupertypeSerializer.class);
    typeFactory.setUnknownAsEntity(true);
}

From source file:com.mysema.query.jpa.codegen.JPADomainExporterTest.java

License:Apache License

private Metamodel convert(Configuration config) {
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(props).buildServiceRegistry();

    config.setProperties(props);/*from w ww.j  a  va 2 s.c  o m*/
    config.buildMappings();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    return MetamodelImpl.buildMetamodel(config.getClassMappings(), (SessionFactoryImplementor) sessionFactory,
            true);
}

From source file:com.premiumminds.persistence.utils.HibernateEnversDDL.java

License:Open Source License

private static void updateCommand(String[] args) {
    String unitName, filename = null, url, username, password;
    if (args.length < 5)
        System.out.println("Expected unitName jdbcUrl jdbcUsername jdbcPassword");
    else {//from  w ww  .  j a  va 2s .  c  om
        unitName = args[1];
        url = args[2];
        username = args[3];
        password = args[4];
        if (args.length > 5)
            filename = args[5];

        Configuration configuration = HibernateDDL.getConfiguration(unitName);
        configuration.buildMappings();
        AuditConfiguration.getFor(configuration);
        Dialect dialect = Dialect.getDialect(configuration.getProperties());

        Connection conn = null;
        DatabaseMetadata meta = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
            meta = new DatabaseMetadata(conn, dialect, true);
            String[] updateSQL = configuration.generateSchemaUpdateScript(dialect, meta);

            HibernateDDL.stringToStream(updateSQL, filename);

            configuration.buildMappings();
            AuditConfiguration.getFor(configuration);
            SchemaUpdate su = new SchemaUpdate(configuration);
            su.setOutputFile(filename);
            su.setFormat(true);
            su.setDelimiter(";");
            su.execute(true, false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.querydsl.jpa.codegen.HibernateDomainExporter.java

License:Apache License

/**
 * Create a new HibernateDomainExporter instance
 *
 * @param namePrefix name prefix (default: Q)
 * @param nameSuffix name suffix (default: empty)
 * @param targetFolder target folder//from   ww  w.  j  a  va 2  s  .  c  o m
 * @param serializerConfig serializer config
 * @param configuration configuration
 * @param charset charset (default: system charset)
 */
public HibernateDomainExporter(String namePrefix, String nameSuffix, File targetFolder,
        SerializerConfig serializerConfig, Configuration configuration, Charset charset) {
    super(namePrefix, nameSuffix, targetFolder, serializerConfig, charset);
    configuration.buildMappings();
    this.configuration = configuration;
}