private void generateDDL() throws Exception { final MetadataImplementor md = createMetaData(); final SchemaExport export = new SchemaExport(md); // drop { export.setDelimiter(";"); export.setOutputFile(getRefPath() + "/db-drop.sql"); export.setFormat(true); export.execute(true, false, true, false); } // create { export.setDelimiter(";"); export.setOutputFile(getRefPath() + "/db-create.sql"); export.setFormat(true); export.execute(true, false, false, true); } }
@SuppressWarnings("unchecked") private void addTableName(MetadataImplementor metadata, ArrayList<String> tables, Table table, String aSchemaName) { String name = (null == aSchemaName) ? "" : aSchemaName + "."; name += table.getName(); if (tables.contains(name)) { return; } final Collection<Table> ts = metadata.collectTableMappings(); for (Table t : ts) { if (t.equals(table)) { continue; } Iterator<ForeignKey> relationships = t.getForeignKeyIterator(); while (relationships.hasNext()) { ForeignKey fk = relationships.next(); if (fk.getReferencedTable().equals(table)) { addTableName(metadata, tables, fk.getTable(), aSchemaName); } } } tables.add(name); }
private void outputDdl(String packageName, String dialect, String fileName) { LocalSessionFactoryBean sfBean = sfBean(packageName, dialect); StandardServiceRegistry serviceRegistry = sfBean.getConfiguration().getStandardServiceRegistryBuilder().build(); try { String outputFile = OutputRoot + fileName; Files.deleteIfExists(Paths.get(outputFile)); MetadataImplementor metadata = metadata(sfBean, serviceRegistry); SchemaExport export = new SchemaExport(); export.setDelimiter(";"); export.setFormat(FormatSql); export.setOutputFile(outputFile); export.create(EnumSet.of(TargetType.SCRIPT), metadata); } catch (Exception e) { throw new InvocationException(e); } finally { StandardServiceRegistryBuilder.destroy( serviceRegistry ); } }
public static SqmDomainMetamodel buildDomainMetamodel(Class... managedClasses) { final MetadataSources metadataSources = new MetadataSources(); for ( Class managedClass : managedClasses ) { metadataSources.addAnnotatedClass( managedClass ); } final MetadataImplementor metadata = (MetadataImplementor) metadataSources.buildMetadata(); metadata.validate(); // at this point we have access to the mapping Metadata (PersistentClass, etc) // use it to build the testing DomainMetamodel/TypeConfiguration final ExplicitSqmDomainMetamodel domainMetamodel = new ExplicitSqmDomainMetamodel( metadata ); populateDatabaseModel( metadata, domainMetamodel ); populateMappingModel( metadata, domainMetamodel ); return domainMetamodel; }
private static void populateMappingModel(MetadataImplementor mappingMetadata, ExplicitSqmDomainMetamodel domainMetamodel) { // final PersisterFactory persisterFactory = getSessionFactory().getServiceRegistry().getService( PersisterFactory.class ); final PersisterFactory persisterFactory = domainMetamodel.getPersisterFactory(); for ( final PersistentClass model : mappingMetadata.getEntityBindings() ) { // final EntityRegionAccessStrategy accessStrategy = getSessionFactory().getCache().determineEntityRegionAccessStrategy( // model // ); final EntityRegionAccessStrategy accessStrategy = null; // final NaturalIdRegionAccessStrategy naturalIdAccessStrategy = getSessionFactory().getCache().determineNaturalIdRegionAccessStrategy( // model // ); final NaturalIdRegionAccessStrategy naturalIdAccessStrategy = null; persisterFactory.createEntityPersister( model, accessStrategy, naturalIdAccessStrategy, domainMetamodel ); } persisterFactory.finishUp( domainMetamodel ); }
protected void export(Class<? extends Dialect> dialect, String app_key, MetadataSources metadata, boolean create, boolean drop) { Assert.notNull(dialect, "dialect is invalid [null]"); Assert.notNull(app_key, "app_key is invalid [null]"); Assert.notNull(metadata, "metadata is invalid [null]"); SchemaExport schemaExport = new SchemaExport((MetadataImplementor) metadata.buildMetadata()); schemaExport.setDelimiter(";"); schemaExport.setFormat(true); if (create) { // Generate create script schemaExport.setOutputFile(String.format("target/%s_ddl_%s_create.sql", app_key, dialect.getSimpleName())); schemaExport.execute(true, false, false, true); } if (drop) { // Generate drop script schemaExport.setOutputFile(String.format("target/%s_ddl_%s_drop.sql", app_key, dialect.getSimpleName())); schemaExport.execute(true, false, true, false); } }
public static MetadataImplementor createMetadataImplementor(String dialect, String[] hibernatePackagesToScan) { final MetadataSources metadata = new MetadataSources( new StandardServiceRegistryBuilder() .applySetting("hibernate.dialect", dialect) .build()); for (String packageName : hibernatePackagesToScan) { for (Class clazz : HibernateMetaDataHelper.getClasses(packageName)) { metadata.addAnnotatedClass(clazz); } } return (MetadataImplementor) metadata.buildMetadata(); }
protected void afterContextInitialization() { this.dataSource = applicationContext.getBean(DataSource.class); final Environment env = applicationContext.getBean(Environment.class); final String dialect = env.getRequiredProperty("spring.jpa.database-platform"); final String[] hibernatePackagesToScan = new String[]{DbActivity.class.getPackage().getName()}; final MetadataImplementor metadataImplementor = HibernateMetaDataHelper.createMetadataImplementor(dialect, hibernatePackagesToScan); truncater = new HibernateMetaDataTruncater(dataSource, metadataImplementor); }
@Test public void testDbSchema() { MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder() .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").build()); metadata.addAnnotatedClass(ConsoleEntity.class); metadata.addAnnotatedClass(GameEntity.class); metadata.addAnnotatedClass(UserEntity.class); metadata.addAnnotatedClass(RoleEntity.class); metadata.addAnnotatedClass(LibraryEntity.class); metadata.addAnnotatedClass(BorrowEntity.class); SchemaExport export = new SchemaExport((MetadataImplementor) metadata.buildMetadata()); export.create(Target.SCRIPT); }
@Override public void prepare(JdbcServices jdbcServices, JdbcConnectionAccess connectionAccess, MetadataImplementor metadata, SessionFactoryOptions sessionFactoryOptions) { ConfigurationService configService = sessionFactoryOptions.getServiceRegistry().getService(ConfigurationService.class); this.fullyQualifiedTableName = Objects.requireNonNull(configService.getSetting(TABLE, String.class, null), "Property " + TABLE + " must be set."); this.idColumn = configService.getSetting(ID_COLUMN, String.class, "ID"); this.discriminatorColumn = configService.getSetting(DISCRIMINATOR_COLUMN, String.class, "ENTITY_NAME"); this.cleanRows = configService.getSetting(CLEAN_ROWS, StandardConverters.BOOLEAN, false); }
@Test public void testSchemaExport() { ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); MetadataImplementor metadataImplementor = (MetadataImplementor) new MetadataSources(serviceRegistry).buildMetadata(); SchemaExport schemaExport = new SchemaExport(serviceRegistry, metadataImplementor); schemaExport.create(true, true); }
private static void populateDatabaseModel(MetadataImplementor metadata, ExplicitSqmDomainMetamodel domainMetamodel) { final Database database = metadata.getDatabase(); final DatabaseModelImpl databaseModel = (DatabaseModelImpl) domainMetamodel.getDatabaseModel(); // todo : apply PhysicalNamingStrategy here, rather than as we create the "mapping model"? // todo : we need DatabaseModel to incorporate catalogs/schemas in some fashion // either like org.hibernate.boot.model.relational.Database does // or via catalogs/schemas-specific names for ( Namespace namespace : database.getNamespaces() ) { for ( Table mappingTable : namespace.getTables() ) { // todo : incorporate mapping Table's isAbstract indicator final org.hibernate.orm.persister.common.spi.Table table; if ( mappingTable instanceof DenormalizedTable ) { // this is akin to a UnionSubclassTable throw new NotYetImplementedException( "DenormalizedTable support not yet implemented" ); } else if ( mappingTable.getSubselect() != null ) { table = new DerivedTable( mappingTable.getSubselect() ); } else { // final JdbcEnvironment jdbcEnvironment = sessionFactory.getJdbcServices().getJdbcEnvironment(); // final String qualifiedTableName = jdbcEnvironment.getQualifiedObjectNameFormatter().format( // mappingTable.getQualifiedTableName(), // jdbcEnvironment.getDialect() // ); final String qualifiedTableName = mappingTable.getQualifiedTableName().render(); table = new PhysicalTable( qualifiedTableName ); } databaseModel.registerTable( table ); } } }
@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); schemaExport.execute(false, true, false, true); if (!schemaExport.getExceptions().isEmpty()) { throw new RuntimeException(schemaExport.getExceptions().toString()); } LATEST_HIBERNATE_STORE = new AbstractHibernateStore.Builder(metadataImplementor.buildSessionFactory()) .withScrollEnabled(true) .withScrollMode(ScrollMode.FORWARD_ONLY) .build(); BridgeableRedisStore hbaseStore = new BridgeableRedisStore(); return new MultiplexManager(LATEST_HIBERNATE_STORE, hbaseStore); }
@Override public void prepare( JdbcServices jdbcServices, JdbcConnectionAccess jdbcConnectionAccess, MetadataImplementor metadataImplementor, SessionFactoryOptions sessionFactoryOptions) { }
private MetadataImplementor createMetaData() throws Exception { return HibernateMetaDataHelper.createMetadataImplementor(getDialect(), getHibernatePackagesToScan()); }
public HibernateMetaDataTruncater(DataSource dataSource, MetadataImplementor configuration) { this.dataSource = dataSource; this.metadata = configuration; }
private SessionFactory newSessionFactory() { final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder() .enableAutoClose(); Integrator integrator = integrator(); if (integrator != null) { bsrb.applyIntegrator(integrator); } final BootstrapServiceRegistry bsr = bsrb.build(); final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr) .applySettings(properties()) .build(); final MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class annotatedClass : entities()) { metadataSources.addAnnotatedClass(annotatedClass); } String[] packages = packages(); if (packages != null) { for (String annotatedPackage : packages) { metadataSources.addPackage(annotatedPackage); } } String[] resources = resources(); if (resources != null) { for (String resource : resources) { metadataSources.addResource(resource); } } final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(); metadataBuilder.enableNewIdentifierGeneratorSupport(true); metadataBuilder.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE); MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build(); final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder(); Interceptor interceptor = interceptor(); if (interceptor != null) { sfb.applyInterceptor(interceptor); } return sfb.build(); }
@Override public SessionFactoryBuilder getSessionFactoryBuilder( MetadataImplementor metadataImplementor, SessionFactoryBuilderImplementor defaultBuilder ) { HibernateMetadata.metadataImplementor.set( metadataImplementor ); return defaultBuilder; }
public static MetadataImplementor getMetadataImplementor() { return metadataImplementor.get(); }
public ExplicitSqmDomainMetamodel(MetadataImplementor mappingMetadata) { this.mappingMetadata = mappingMetadata; }
@Override public MetadataImplementor getMetadata() { return mappingMetadata; }
@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 { 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 AbstractHibernateStore.Builder(metadataImplementor.buildSessionFactory()) .withScrollEnabled(true) .withScrollMode(ScrollMode.FORWARD_ONLY) .build(); }
private SessionFactory newSessionFactory() { final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder() .enableAutoClose(); Integrator integrator = integrator(); if (integrator != null) { bsrb.applyIntegrator( integrator ); } final BootstrapServiceRegistry bsr = bsrb.build(); final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bsr) .applySettings(properties()) .build(); final MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class annotatedClass : entities()) { metadataSources.addAnnotatedClass(annotatedClass); } String[] packages = packages(); if (packages != null) { for (String annotatedPackage : packages) { metadataSources.addPackage(annotatedPackage); } } String[] resources = resources(); if (resources != null) { for (String resource : resources) { metadataSources.addResource(resource); } } final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(); metadataBuilder.enableNewIdentifierGeneratorSupport(true); metadataBuilder.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE); final List<Type> additionalTypes = additionalTypes(); if (additionalTypes != null) { additionalTypes.stream().forEach(type -> { metadataBuilder.applyTypes((typeContributions, serviceRegistry1) -> { if(type instanceof BasicType) { typeContributions.contributeType((BasicType) type); } else if (type instanceof UserType ){ typeContributions.contributeType((UserType) type); } else if (type instanceof CompositeUserType) { typeContributions.contributeType((CompositeUserType) type); } }); }); } MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build(); final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder(); Interceptor interceptor = interceptor(); if(interceptor != null) { sfb.applyInterceptor(interceptor); } return sfb.build(); }
@SuppressWarnings("static-access") @Override public SessionFactoryBuilder getSessionFactoryBuilder(MetadataImplementor metadata, SessionFactoryBuilderImplementor defaultBuilder) { this.metadata = metadata; return defaultBuilder; // Just return the one provided in the argument itself. All we care about is the metadata :) }
public static MetadataImplementor getMetadata() { return metadata; }