Example usage for org.hibernate.boot MetadataSources buildMetadata

List of usage examples for org.hibernate.boot MetadataSources buildMetadata

Introduction

In this page you can find the example usage for org.hibernate.boot MetadataSources buildMetadata.

Prototype

public Metadata buildMetadata() 

Source Link

Document

Short-hand form of calling #getMetadataBuilder() and using its org.hibernate.boot.MetadataBuilder#build() method in cases where the application wants to accept the defaults.

Usage

From source file:com.abcanthur.website.codegenhack.JPADatabase.java

License:Apache License

@SuppressWarnings("serial")
@Override/*  w ww  . j a  v  a2 s  .  c om*/
protected DSLContext create0() {
    if (connection == null) {
        String packages = getProperties().getProperty("packages");

        if (isBlank(packages)) {
            packages = "";
            log.warn("No packages defined",
                    "It is highly recommended that you provide explicit packages to scan");
        }

        try {
            connection = DriverManager.getConnection("jdbc:h2:mem:jooq-meta-extensions", "sa", "");

            MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
                    .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
                    .applySetting("javax.persistence.schema-generation-connection", connection)

                    // [#5607] JPADatabase causes warnings - This prevents them
                    .applySetting(AvailableSettings.CONNECTION_PROVIDER,
                            "com.abcanthur.website.codegenhack.CustomConnectionProvider")
                    .build());

            ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
                    true);

            scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
            for (String pkg : packages.split(","))
                for (BeanDefinition def : scanner.findCandidateComponents(defaultIfBlank(pkg, "").trim()))
                    metadata.addAnnotatedClass(Class.forName(def.getBeanClassName()));

            // This seems to be the way to do this in idiomatic Hibernate 5.0 API
            // See also: http://stackoverflow.com/q/32178041/521799
            // SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), connection);
            // export.create(true, true);

            // Hibernate 5.2 broke 5.0 API again. Here's how to do this now:
            SchemaExport export = new SchemaExport();
            export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
        } catch (Exception e) {
            throw new DataAccessException("Error while exporting schema", e);
        }
    }

    return DSL.using(connection);
}

From source file:com.devnexus.ting.core.dao.hibernate.SystemDaoHibernate.java

License:Apache License

@Override
public void createDatabase(boolean outputOnly, String dialect) {

    final Map<String, Object> propertyMap = fb.getJpaPropertyMap();

    final Map<String, Object> localPropertyMap = new HashMap<>(propertyMap);

    if (dialect != null) {
        localPropertyMap.put("hibernate.dialect", dialect);
    }//  w ww. j  a  v  a  2  s  .c om

    final MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
            .applySetting("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect")
            .applySetting("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName())
            .applySetting("hibernate.implicit_naming_strategy",
                    DevNexusSpringImplicitNamingStrategy.class.getName())
            .applySettings(localPropertyMap).build());

    for (Class<?> clazz : PersistenceConfig.getAnnotatedPersistenceClasses()) {
        metadata.addAnnotatedClass(clazz);
    }
    final SchemaExport export;
    try {
        export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), dataSource.getConnection());
    } catch (HibernateException | SQLException e) {
        throw new IllegalStateException(e);
    }
    export.create(true, !outputOnly);

}

From source file:com.evolveum.midpoint.repo.sql.SchemaTest.java

License:Apache License

private void createSQLSchema(String fileName, String dialect) {
    File file = new File(fileName);
    if (file.exists()) {
        file.delete();/*from  w  ww  . ja v a  2 s.  com*/
    }

    MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder()
            .applySetting("hibernate.implicit_naming_strategy", new MidPointImplicitNamingStrategy())
            .applySetting("hibernate.physical_naming_strategy", new MidPointPhysicalNamingStrategy())
            .applySetting("hibernate.dialect", dialect).build());

    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.container", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.any", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.embedded", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.enums", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.id", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.other", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.common.type", metadata);
    addAnnotatedClasses("com.evolveum.midpoint.repo.sql.data.audit", metadata);

    metadata.addPackage("com.evolveum.midpoint.repo.sql.type");

    SchemaExport export = new SchemaExport();
    export.setOutputFile(fileName);
    export.setDelimiter(";");
    //        export.setFormat(true);
    export.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadata.buildMetadata());
}

From source file:com.imos.sample.service.HibernateService.java

/**
 * Hibernate configuration./*  www .  jav a  2 s .c om*/
 *
 * @throws RepositoryException
 */
public void config() throws RepositoryException {
    try {
        StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
        if (filePath == null || filePath.isEmpty()) {
            registryBuilder = registryBuilder.configure();
        } else {
            registryBuilder = registryBuilder.configure(filePath);
        }
        registry = registryBuilder.build();

        MetadataSources metaData = new MetadataSources(registry);
        sessionFactory = metaData.buildMetadata().buildSessionFactory();
        session = sessionFactory.openSession();

        SchemaExport schemaExport = new SchemaExport();
        schemaExport.setDelimiter(";");
        schemaExport.setFormat(true);
        schemaExport.setManageNamespaces(true);
        schemaExport.setOutputFile("./ddl_skilldb.sql");
        schemaExport.execute(EnumSet.of(TargetType.SCRIPT, TargetType.DATABASE, TargetType.STDOUT),
                SchemaExport.Action.CREATE, metaData.buildMetadata(registry), registry);

        log.info("Configuration succeed");
    } catch (HibernateException e) {
        StandardServiceRegistryBuilder.destroy(registry);
        log.error("Configuration failed : {}", e);
    }
}

From source file:com.yahoo.elide.datastores.hibernate5.HibernateDataStoreSupplier.java

License:Apache License

@Override
public DataStore get() {
    // Add additional checks to our static check mappings map.
    // NOTE: This is a bit hacky. We need to do a major overhaul on our test architecture
    TestCheckMappings.MAPPINGS.put("filterCheck", Filtered.FilterCheck.class);
    TestCheckMappings.MAPPINGS.put("filterCheck3", Filtered.FilterCheck3.class);

    // method to force class initialization
    MetadataSources metadataSources = new MetadataSources(new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml").applySetting(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .applySetting(Environment.URL,
                    "jdbc:mysql://localhost:" + System.getProperty("mysql.port", "3306")
                            + "/root?serverTimezone=UTC")
            .applySetting(Environment.USER, "root").applySetting(Environment.PASS, "root").build());

    try {/*from   w  w  w.  j  a v  a 2s .  c  om*/
        ClassScanner.getAnnotatedClasses(Parent.class.getPackage(), Entity.class)
                .forEach(metadataSources::addAnnotatedClass);
    } catch (MappingException e) {
        throw new RuntimeException(e);
    }

    MetadataImplementor metadataImplementor = (MetadataImplementor) metadataSources.buildMetadata();

    // create example tables from beans
    SchemaExport schemaExport = new SchemaExport(metadataImplementor); //.setHaltOnError(true);
    schemaExport.drop(false, true);
    schemaExport.execute(false, true, false, true);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException(schemaExport.getExceptions().toString());
    }

    return new HibernateStore(metadataImplementor.buildSessionFactory(), true, ScrollMode.FORWARD_ONLY);
}

From source file:com.yahoo.elide.datastores.hibernate5.HibernateEntityManagerDataStoreSupplier.java

License:Apache License

@Override
public DataStore get() {
    // Add additional checks to our static check mappings map.
    // NOTE: This is a bit hacky. We need to do a major overhaul on our test architecture
    TestCheckMappings.MAPPINGS.put("filterCheck", Filtered.FilterCheck.class);
    TestCheckMappings.MAPPINGS.put("filterCheck3", Filtered.FilterCheck3.class);

    Map<String, Object> options = new HashMap<>();
    ArrayList<Class> bindClasses = new ArrayList<>();

    try {/*from  w  w  w.ja v  a  2s. co m*/
        bindClasses.addAll(ClassScanner.getAnnotatedClasses(Parent.class.getPackage(), Entity.class));
    } catch (MappingException e) {
        throw new IllegalStateException(e);
    }

    options.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
    options.put("javax.persistence.jdbc.url",
            JDBC_PREFIX + System.getProperty(MYSQL_PORT_PROPERTY, MYSQL_PORT) + JDBC_SUFFIX);
    options.put("javax.persistence.jdbc.user", ROOT);
    options.put("javax.persistence.jdbc.password", ROOT);
    options.put(AvailableSettings.LOADED_CLASSES, bindClasses);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("elide-tests", options);
    HibernateEntityManager em = (HibernateEntityManager) emf.createEntityManager();

    // method to force class initialization
    MetadataSources metadataSources = new MetadataSources(new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml").applySetting(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .applySetting(Environment.URL,
                    JDBC_PREFIX + System.getProperty(MYSQL_PORT_PROPERTY, MYSQL_PORT) + JDBC_SUFFIX)
            .applySetting(Environment.USER, ROOT).applySetting(Environment.PASS, ROOT).build());

    try {
        ClassScanner.getAnnotatedClasses(Parent.class.getPackage(), Entity.class)
                .forEach(metadataSources::addAnnotatedClass);
    } catch (MappingException e) {
        throw new IllegalStateException(e);
    }

    MetadataImplementor metadataImplementor = (MetadataImplementor) metadataSources.buildMetadata();

    EnumSet<TargetType> type = EnumSet.of(TargetType.DATABASE);
    // create example tables from beans
    SchemaExport schemaExport = new SchemaExport();
    schemaExport.drop(type, metadataImplementor);
    schemaExport.execute(type, SchemaExport.Action.CREATE, metadataImplementor);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new IllegalStateException(schemaExport.getExceptions().toString());
    }

    return new AbstractHibernateStore.Builder(em).withScrollEnabled(true)
            .withScrollMode(ScrollMode.FORWARD_ONLY).build();
}

From source file:com.yahoo.elide.datastores.multiplex.bridgeable.BridgeableStoreSupplier.java

License:Apache License

@Override
public DataStore get() {
    // method to force class initialization
    MetadataSources metadataSources = new MetadataSources(new StandardServiceRegistryBuilder()
            .configure("hibernate.cfg.xml").applySetting(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread")
            .applySetting(Environment.URL,
                    "jdbc:mysql://localhost:" + System.getProperty("mysql.port", "3306")
                            + "/root?serverTimezone=UTC")
            .applySetting(Environment.USER, "root").applySetting(Environment.PASS, "root").build());

    metadataSources.addAnnotatedClass(HibernateUser.class);

    MetadataImplementor metadataImplementor = (MetadataImplementor) metadataSources.buildMetadata();

    // create example tables from beans
    SchemaExport schemaExport = new SchemaExport(metadataImplementor); //.setHaltOnError(true);
    schemaExport.drop(false, true);//from   w w  w . ja  v  a2s .  co  m
    schemaExport.execute(false, true, false, true);

    if (!schemaExport.getExceptions().isEmpty()) {
        throw new RuntimeException(schemaExport.getExceptions().toString());
    }

    LATEST_HIBERNATE_STORE = new HibernateStore.Builder(metadataImplementor.buildSessionFactory())
            .withScrollEnabled(true).withScrollMode(ScrollMode.FORWARD_ONLY).build();

    BridgeableRedisStore hbaseStore = new BridgeableRedisStore();

    return new MultiplexManager(LATEST_HIBERNATE_STORE, hbaseStore);
}

From source file:DAO.Hibernate.AccountDAOHibernate.java

public SessionFactory getSessionFactory() {
    StandardServiceRegistry ssrb = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
    MetadataSources ms = new MetadataSources(ssrb);
    ms.addAnnotatedClass(Klant.class);
    ms.addAnnotatedClass(Adres.class);
    ms.addAnnotatedClass(Account.class);
    SessionFactory sf = ms.buildMetadata().buildSessionFactory();
    return sf;/* www . j  av a 2  s  . co m*/
}

From source file:DAO.Hibernate.ArtikelDAOHibernate.java

public SessionFactory getSessionFactory() {
    StandardServiceRegistry ssrb = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
    MetadataSources ms = new MetadataSources(ssrb);
    ms.addAnnotatedClass(Artikel.class);
    SessionFactory sf = ms.buildMetadata().buildSessionFactory();
    return sf;/*w w  w . j ava2s.  c  om*/
}

From source file:DAO.Hibernate.BestellingArtikelDAOHibernate.java

public SessionFactory getSessionFactory() {
    StandardServiceRegistry ssrb = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
    MetadataSources ms = new MetadataSources(ssrb);
    ms.addAnnotatedClass(Bestelling.class);
    ms.addAnnotatedClass(BestellingArtikel.class);
    ms.addAnnotatedClass(Artikel.class);
    SessionFactory sf = ms.buildMetadata().buildSessionFactory();
    return sf;/*  w ww  . j av  a2 s . c o m*/
}