Example usage for org.hibernate.boot.registry BootstrapServiceRegistryBuilder BootstrapServiceRegistryBuilder

List of usage examples for org.hibernate.boot.registry BootstrapServiceRegistryBuilder BootstrapServiceRegistryBuilder

Introduction

In this page you can find the example usage for org.hibernate.boot.registry BootstrapServiceRegistryBuilder BootstrapServiceRegistryBuilder.

Prototype

BootstrapServiceRegistryBuilder

Source Link

Usage

From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBean.java

License:Apache License

/**
 * Determine the Hibernate {@link MetadataSources} to use.
 * <p>// w  ww .  java2  s  .  c o  m
 * Can also be externally called to initialize and pre-populate a
 * {@link MetadataSources} instance which is then going to be used for
 * {@link SessionFactory} building.
 *
 * @return the MetadataSources to use (never {@code null})
 * @see HibernateSpringSessionFactoryBuilder#HibernateSpringSessionFactoryBuilder(DataSource,
 * ResourceLoader, MetadataSources)
 * @since 4.3
 */
public MetadataSources getMetadataSources() {
    if (this.metadataSources == null) {
        BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder();
        if (this.resourcePatternResolver != null) {
            builder = builder.applyClassLoader(this.resourcePatternResolver.getClassLoader());
        }
        this.metadataSources = new MetadataSources(builder.build());
    }
    return this.metadataSources;
}

From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBuilder.java

License:Apache License

/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 *
 * @param dataSource     the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 *                       (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 *///  ww  w . j  a va2s  .  c  o m
public HibernateSpringSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
    this(dataSource, resourceLoader, new MetadataSources(
            new BootstrapServiceRegistryBuilder().applyClassLoader(resourceLoader.getClassLoader()).build()));
}

From source file:com.foilen.smalltools.tools.Hibernate50Tools.java

License:Open Source License

/**
 * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)}
 *
 * @param dialect// ww  w.j  ava  2  s . c  o m
 *            the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect )
 * @param outputSqlFile
 *            where to put the generated SQL file
 * @param useUnderscore
 *            true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager"
 * @param packagesToScan
 *            the packages where your entities are
 */
public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile,
        boolean useUnderscore, String... packagesToScan) {

    BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder().build();

    MetadataSources metadataSources = new MetadataSources(bootstrapServiceRegistry);

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(MappedSuperclass.class));
    for (String pkg : packagesToScan) {
        for (BeanDefinition beanDefinition : scanner.findCandidateComponents(pkg)) {
            metadataSources.addAnnotatedClassName(beanDefinition.getBeanClassName());
        }
    }

    StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder(
            bootstrapServiceRegistry);
    standardServiceRegistryBuilder.applySetting(AvailableSettings.DIALECT, dialect.getName());
    StandardServiceRegistryImpl ssr = (StandardServiceRegistryImpl) standardServiceRegistryBuilder.build();
    MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(ssr);

    if (useUnderscore) {
        metadataBuilder.applyImplicitNamingStrategy(new SpringImplicitNamingStrategy());
        metadataBuilder.applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy());
    }

    MetadataImpl metadata = (MetadataImpl) metadataBuilder.build();

    // Exportation
    SchemaExport schemaExport = new SchemaExport(metadata);
    schemaExport.setOutputFile(outputSqlFile);
    schemaExport.setDelimiter(";");
    schemaExport.setFormat(true);
    schemaExport.execute(true, false, false, true);
}

From source file:com.foilen.smalltools.tools.Hibernate51Tools.java

License:Open Source License

/**
 * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)}
 *
 * @param dialect//from  w  ww  .j a v a2 s.  c om
 *            the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect )
 * @param outputSqlFile
 *            where to put the generated SQL file
 * @param useUnderscore
 *            true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager"
 * @param packagesToScan
 *            the packages where your entities are
 */
public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile,
        boolean useUnderscore, String... packagesToScan) {

    BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder().build();

    MetadataSources metadataSources = new MetadataSources(bootstrapServiceRegistry);

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(MappedSuperclass.class));
    for (String pkg : packagesToScan) {
        for (BeanDefinition beanDefinition : scanner.findCandidateComponents(pkg)) {
            metadataSources.addAnnotatedClassName(beanDefinition.getBeanClassName());
        }
    }

    StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder(
            bootstrapServiceRegistry);
    standardServiceRegistryBuilder.applySetting(AvailableSettings.DIALECT, dialect.getName());
    StandardServiceRegistryImpl ssr = (StandardServiceRegistryImpl) standardServiceRegistryBuilder.build();
    MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(ssr);

    if (useUnderscore) {
        metadataBuilder.applyImplicitNamingStrategy(new SpringImplicitNamingStrategy());
        metadataBuilder.applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy());
    }

    new SchemaExport() //
            .setHaltOnError(true) //
            .setOutputFile(outputSqlFile) //
            .setFormat(true) //
            .setDelimiter(";") //
            .execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadataBuilder.build());

}

From source file:com.zeroone.guestebook.domain.SchemaGenerator.java

License:Apache License

public SchemaGenerator(String packageName, Dialect dialect) throws Exception {
    BootstrapServiceRegistry bsr;/* w  w w .  j a  va  2  s  . co m*/
    bsr = new BootstrapServiceRegistryBuilder().build();
    StandardServiceRegistryBuilder ssrBuilder;
    ssrBuilder = new StandardServiceRegistryBuilder(bsr);
    ssrBuilder.applySetting("hibernate.dialect", dialect.dialectClass);
    ServiceRegistry serviceRegistry = ssrBuilder.build();
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    for (Class<?> clazz : getClasses(packageName)) {
        metadataSources.addAnnotatedClass(clazz);
    }
    MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder();
    this.metadata = (MetadataImplementor) metadataBuilder.build();
    this.dialect = dialect;
}

From source file:org.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.java

License:Apache License

@Override
public SessionFactory buildSessionFactory() throws HibernateException {

    // set the class loader to load Groovy classes

    // work around for HHH-2624
    Map<String, Type> empty = new HashMap<String, Type>();
    addFilterDefinition(new FilterDefinition("dynamicFilterEnabler", "1=1", empty));

    SessionFactory sessionFactory = null;

    ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER);
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (appClassLoader != null && !appClassLoader.equals(threadContextClassLoader));
    if (overrideClassLoader) {
        currentThread.setContextClassLoader(appClassLoader);
    }/*  w  ww  .  j av  a2  s  .c o  m*/

    try {
        ConfigurationHelper.resolvePlaceHolders(getProperties());

        EventListenerIntegrator eventListenerIntegrator = new EventListenerIntegrator(hibernateEventListeners,
                eventListeners);
        BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder()
                .with(eventListenerIntegrator).build();

        setSessionFactoryObserver(new SessionFactoryObserver() {
            private static final long serialVersionUID = 1;

            public void sessionFactoryCreated(SessionFactory factory) {
            }

            public void sessionFactoryClosed(SessionFactory factory) {
                ((ServiceRegistryImplementor) serviceRegistry).destroy();
            }
        });

        StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder(
                bootstrapServiceRegistry).applySettings(getProperties());
        sessionFactory = super.buildSessionFactory(standardServiceRegistryBuilder.build());
        serviceRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry();
    } finally {
        if (overrideClassLoader) {
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
    }

    return sessionFactory;
}

From source file:org.granite.test.tide.hibernate4.data.TestHibernate4ChangeSetMerge.java

License:Open Source License

@Override
protected void initPersistence() {
    Configuration configuration = new Configuration().addAnnotatedClass(AbstractEntity.class)
            .addAnnotatedClass(Address.class).addAnnotatedClass(Contact1.class).addAnnotatedClass(Country.class)
            .addAnnotatedClass(Person1.class).addAnnotatedClass(Phone.class).addAnnotatedClass(Contact2.class)
            .addAnnotatedClass(Person2.class).addAnnotatedClass(Phone2.class)
            .setProperty("hibernate.dialect", org.hibernate.dialect.H2Dialect.class.getName())
            .setProperty("hibernate.hbm2ddl.auto", "create-drop").setProperty("hibernate.show_sql", "true")
            .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName())
            .setProperty("hibernate.connection.url", "jdbc:h2:mem:test-loader")
            .setProperty("hibernate.connection.username", "sa")
            .setProperty("hibernate.connection.password", "");

    BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
            .with(new Hibernate4ChangeSetIntegrator());
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(bsrb.build())
            .applySettings(configuration.getProperties());
    ServiceRegistry serviceRegistry = ssrb.build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}

From source file:org.granite.test.tide.hibernate4.data.TestHibernate4ChangeSetPublisher.java

License:Open Source License

protected void initPersistence() {
    Configuration configuration = new Configuration().addAnnotatedClass(AbstractEntity.class)
            .addAnnotatedClass(LegalEntity.class).addAnnotatedClass(Address.class)
            .addAnnotatedClass(Contact1.class).addAnnotatedClass(Country.class).addAnnotatedClass(Person1.class)
            .addAnnotatedClass(Person4.class).addAnnotatedClass(Contact4.class).addAnnotatedClass(Phone.class)
            .addAnnotatedClass(Phone2.class).addAnnotatedClass(Phone4.class).addAnnotatedClass(OrderRepo.class)
            .addAnnotatedClass(Order.class).addAnnotatedClass(LineItemList.class)
            .addAnnotatedClass(LineItemBag.class).addAnnotatedClass(Order2.class)
            .addAnnotatedClass(LineItemList2.class).addAnnotatedClass(LineItemBag2.class)
            .addAnnotatedClass(Classification.class)
            .setProperty("hibernate.dialect", org.hibernate.dialect.H2Dialect.class.getName())
            .setProperty("hibernate.hbm2ddl.auto", "create-drop").setProperty("hibernate.show_sql", "true")
            .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName())
            .setProperty("hibernate.connection.url", "jdbc:h2:mem:test-changeset")
            .setProperty("hibernate.connection.username", "sa")
            .setProperty("hibernate.connection.password", "");

    BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
            .with(new Hibernate4ChangeSetIntegrator());
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(bsrb.build())
            .applySettings(configuration.getProperties());
    ServiceRegistry serviceRegistry = ssrb.build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}

From source file:org.granite.test.tide.hibernate4.data.TestHibernate4DataPublish.java

License:Open Source License

protected void initPersistence() throws Exception {
    Configuration configuration = new Configuration().addAnnotatedClass(AbstractEntity0.class)
            .addAnnotatedClass(Order3.class).addAnnotatedClass(LineItem.class).addAnnotatedClass(Contact5.class)
            .addAnnotatedClass(Location5.class).addAnnotatedClass(Alias5.class)
            .setProperty("hibernate.dialect", org.hibernate.dialect.H2Dialect.class.getName())
            .setProperty("hibernate.hbm2ddl.auto", "create-drop").setProperty("hibernate.show_sql", "true")
            .setProperty("hibernate.connection.driver_class", "org.h2.Driver")
            .setProperty("hibernate.connection.url", "jdbc:h2:mem:test-publish")
            .setProperty("hibernate.connection.username", "sa")
            .setProperty("hibernate.connection.password", "");

    BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
            .with(new Hibernate4Integrator());
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(bsrb.build())
            .applySettings(configuration.getProperties());
    ServiceRegistry serviceRegistry = ssrb.build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}

From source file:org.jboss.as.test.integration.hibernate.naturalid.SFSBHibernateSFNaturalId.java

License:Open Source License

public void setupConfig() {
    // static {/*w  w  w. j ava2s  .c  om*/
    try {

        // prepare the configuration
        Configuration configuration = new Configuration()
                .setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
        configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
        configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS");

        // configuration.configure("hibernate.cfg.xml");

        // fetch the properties
        Properties properties = new Properties();
        properties.putAll(configuration.getProperties());

        Environment.verifyProperties(properties);
        ConfigurationHelper.resolvePlaceHolders(properties);

        // build the serviceregistry
        final BootstrapServiceRegistryBuilder bootstrapbuilder = new BootstrapServiceRegistryBuilder();
        serviceRegistry = builder.build();

        // Create the SessionFactory from Configuration
        sessionFactory = configuration.configure("hibernate.cfg.xml").buildSessionFactory(serviceRegistry);

    } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        // ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }

}