Example usage for org.hibernate.boot MetadataSources addAnnotatedClass

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

Introduction

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

Prototype

public MetadataSources addAnnotatedClass(Class annotatedClass) 

Source Link

Document

Read metadata from the annotations attached to the given class.

Usage

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

License:Apache License

@SuppressWarnings("serial")
@Override//from   ww  w.  j  a  v  a  2s. c  o m
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.booleanworks.peacockmantisshrimp.modules.hibernate.mongodbogm.HibernateOgmBootstapper.java

public boolean bootstrap() throws OgmHelperException {

    this.checkConfigurationAndUpdateStatus();

    if (this.getStatus() != Status.goodConfiguration) {
        Logger.getLogger(this.getClass().getCanonicalName()).log(Level.SEVERE,
                "Bootstrapper seems to be in a bad configuration... aborting.");
        return false;
    }/*from   www .ja v a 2 s. co  m*/

    if (this.getStatus() == Status.bootstrapping) {
        throw new OgmHelperException("already bootstrapping  !!");
    }

    this.setStatus(Status.bootstrapping);

    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();

    //And specific config
    ssrb.applySetting(OgmProperties.ENABLED, true);

    //assuming you are using JTA in a non container environment
    //ssrb.applySetting(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta");
    //assuming JBoss TransactionManager in standalone mode
    //ssrb.applySetting(AvailableSettings.JTA_PLATFORM, "JBossTS");
    //Using provided settings
    ssrb.applySettings(this.getSettings());

    if (this.getSettings().containsKey(OgmProperties.DATASTORE_PROVIDER)) {
        String providerValue = (String) this.getSettings().get(OgmProperties.DATASTORE_PROVIDER);

        if (providerValue.toLowerCase().equals("mongodb")) {
            Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO,
                    "Detecting MongoDb provider.... doing additional checks");
            if (!this.getSettings().containsKey(MongoDBProperties.AUTHENTICATION_MECHANISM)) {
                AuthenticationMechanismType authenticationMechanismType = AuthenticationMechanismType.SCRAM_SHA_1;

                Logger.getLogger(this.getClass().getCanonicalName()).log(Level.WARNING,
                        "No MongoDb authentication mecanism set, patching configuration, setting to "
                                + authenticationMechanismType.name());
                this.getSettings().put(MongoDBProperties.AUTHENTICATION_MECHANISM, authenticationMechanismType);

                Logger.getLogger(this.getClass().getCanonicalName()).log(Level.WARNING,
                        "Current setings are: " + this.getSettings().toString());
            }
        }

    }

    //saving ssrb
    this.setStandardServiceRegistryBuilder(ssrb);

    //building registry
    StandardServiceRegistry registry = ssrb.build();
    if (registry == null) {
        throw new OgmHelperException("Failed to get a registry !!");
    }

    //saving registry
    this.setStandardServiceRegistry(registry);

    MetadataSources ms = new MetadataSources(registry);

    for (Class cEntity : this.getDeclaredEntities()) {
        ms.addAnnotatedClass(cEntity);
        Logger.getLogger(this.getClass().getCanonicalName()).log(Level.INFO,
                "Added entity: " + cEntity.getCanonicalName());
    }

    Metadata md = ms.buildMetadata(registry);

    SessionFactoryBuilder sfb = md.getSessionFactoryBuilder();

    OgmSessionFactory osf = sfb.unwrap(OgmSessionFactoryBuilder.class).build();

    //Saving the MetadataSources
    this.setMetadataSources(ms);

    //Saving SessionFactoryBuilder
    this.setSessionFactoryBuilder(sfb);

    //Savinf the OgmSessionFactory 
    this.setOgmSessionFactory(osf);

    this.setStatus(Status.ready);

    return true;
}

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);
    }/*from ww  w  .j  av a 2  s .  c  o  m*/

    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 addAnnotatedClasses(String packageName, MetadataSources metadata) {
    Set<Class> classes = ClassPathUtil.listClasses(packageName);
    for (Class clazz : classes) {
        metadata.addAnnotatedClass(clazz);
    }/*from w  ww . j  av a  2 s.  c  om*/
}

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  .j  a  v a2 s.c o 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:com.zeroone.guestebook.domain.SchemaGenerator.java

License:Apache License

public SchemaGenerator(String packageName, Dialect dialect) throws Exception {
    BootstrapServiceRegistry bsr;//from w w w  .j av  a2  s.  c om
    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: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;//  w ww .  j a v  a 2 s  . c  o 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;/*  ww  w .ja va2 s.co  m*/
}

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;//from  w w w.  j  a v  a2 s.c om
}

From source file:DAO.Hibernate.BestellingDAOHibernate.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);
    ms.addAnnotatedClass(Klant.class);
    ms.addAnnotatedClass(Account.class);
    ms.addAnnotatedClass(Adres.class);
    SessionFactory sf = ms.buildMetadata().buildSessionFactory();
    return sf;/*from www  .  j  av  a  2  s. c om*/
}