org.hibernate.boot.Metadata Java Examples
The following examples show how to use
org.hibernate.boot.Metadata.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultUniqueDelegate.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public String getAlterTableToDropUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata) { final JdbcEnvironment jdbcEnvironment = metadata.getDatabase().getJdbcEnvironment(); final String tableName = jdbcEnvironment.getQualifiedObjectNameFormatter().format( uniqueKey.getTable().getQualifiedTableName(), dialect ); final StringBuilder buf = new StringBuilder( dialect.getAlterTableString(tableName) ); buf.append( getDropUnique() ); if ( dialect.supportsIfExistsBeforeConstraintName() ) { buf.append( "if exists " ); } buf.append( dialect.quote( uniqueKey.getName() ) ); if ( dialect.supportsIfExistsAfterConstraintName() ) { buf.append( " if exists" ); } return buf.toString(); }
Example #2
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
private static SessionFactory buildSessionFactory(Strategy strategy) { try { ServiceRegistry serviceRegistry = configureServiceRegistry(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class<?> entityClass : strategy.getEntityClasses()) { metadataSources.addAnnotatedClass(entityClass); } Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); } catch (IOException ex) { throw new ExceptionInInitializerError(ex); } }
Example #3
Source File: DbInitializer.java From cosmo with Apache License 2.0 | 6 votes |
/** * Schema validation */ // TODO private void validateSchema() { try { SessionFactory factory = this.localSessionFactory.unwrap(SessionFactory.class); StandardServiceRegistry registry = factory.getSessionFactoryOptions().getServiceRegistry(); MetadataSources sources = new MetadataSources(registry); sources.addPackage("org.unitedinternet.cosmo.model.hibernate"); Metadata metadata = sources.buildMetadata(registry); new SchemaValidator().validate(metadata); LOG.info("Schema validation passed"); } catch (HibernateException e) { LOG.error("error validating schema", e); throw e; } }
Example #4
Source File: TransactionsTest.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void jdbc() { //tag::transactions-api-jdbc-example[] StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() // "jdbc" is the default, but for explicitness .applySetting( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jdbc" ) .build(); Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( Customer.class ) .getMetadataBuilder() .build(); SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() .build(); Session session = sessionFactory.openSession(); try { // calls Connection#setAutoCommit( false ) to // signal start of transaction session.getTransaction().begin(); session.createQuery( "UPDATE customer set NAME = 'Sir. '||NAME" ) .executeUpdate(); // calls Connection#commit(), if an error // happens we attempt a rollback session.getTransaction().commit(); } catch ( Exception e ) { // we may need to rollback depending on // where the exception happened if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) { session.getTransaction().rollback(); } // handle the underlying error } finally { session.close(); sessionFactory.close(); } //end::transactions-api-jdbc-example[] }
Example #5
Source File: ClassImportIntegrator.java From hibernate-types with Apache License 2.0 | 6 votes |
/** * Register the provided classes by their simple name or relative package and class name. * * @param metadata metadata * @param sessionFactory Hibernate session factory * @param serviceRegistry Hibernate service registry */ @Override public void integrate( Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { for(Class classImport : classImportList) { String key; if(excludedPath != null) { key = classImport.getName().replace(excludedPath, ""); } else { key = classImport.getSimpleName(); } metadata.getImports().put( key, classImport.getName() ); } }
Example #6
Source File: IndividuallySchemaValidatorImpl.java From lams with GNU General Public License v2.0 | 6 votes |
@Override protected void validateTables( Metadata metadata, DatabaseInformation databaseInformation, ExecutionOptions options, Dialect dialect, Namespace namespace) { for ( Table table : namespace.getTables() ) { if ( schemaFilter.includeTable( table ) && table.isPhysicalTable() ) { final TableInformation tableInformation = databaseInformation.getTableInformation( table.getQualifiedTableName() ); validateTable( table, tableInformation, metadata, options, dialect ); } } }
Example #7
Source File: TableDependencyTracker.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
/** * Initializes the table dependency tracker. * * @param metadata the Hibernate metadata * @param schemaAction the kind of schema operation being done: {CREATE or DROP}. */ public void initializeDependencies(Metadata metadata, Action schemaAction) { HashMap<Table, Table> dependencies = new HashMap<>(); for (Table childTable : metadata.collectTableMappings()) { Interleaved interleaved = SchemaUtils.getInterleaveAnnotation(childTable, metadata); if (interleaved != null) { if (schemaAction == Action.CREATE || schemaAction == Action.UPDATE) { // If creating tables, the parent blocks the child. dependencies.put(childTable, SchemaUtils.getTable(interleaved.parentEntity(), metadata)); } else { // If dropping tables, the child blocks the parent. dependencies.put(SchemaUtils.getTable(interleaved.parentEntity(), metadata), childTable); } } } this.tableDependencies = dependencies; this.processedTables = new HashSet<>(); }
Example #8
Source File: SpannerTableStatements.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
private void addStatementAfterDdlBatch(Metadata metadata, String statement) { // Find the RunBatchDdl auxiliary object which can run statements after the DDL batch. Optional<RunBatchDdl> runBatchDdl = metadata.getDatabase().getAuxiliaryDatabaseObjects().stream() .filter(obj -> obj instanceof RunBatchDdl) .map(obj -> (RunBatchDdl) obj) .findFirst(); if (runBatchDdl.isPresent()) { runBatchDdl.get().addAfterDdlStatement(statement); } else { throw new IllegalStateException( "Failed to generate INSERT statement for the hibernate_sequence table. " + "The Spanner dialect did not create auxiliary database objects correctly. " + "Please post a question to " + "https://github.com/GoogleCloudPlatform/google-cloud-spanner-hibernate/issues"); } }
Example #9
Source File: SpannerTableStatements.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
private static List<Column> getSortedPkColumns(Table table, Metadata metadata) { Interleaved interleaved = SchemaUtils.getInterleaveAnnotation(table, metadata); if (interleaved == null) { return table.getPrimaryKey().getColumns(); } Table parentTable = SchemaUtils.getTable(interleaved.parentEntity(), metadata); List<Column> sortedParentPkColumns = getSortedPkColumns(parentTable, metadata); List<Column> sortedCurrentPkColumns = table.getPrimaryKey().getColumns().stream() .filter(column -> !sortedParentPkColumns.contains(column)) .collect(Collectors.toList()); ArrayList<Column> currentPkColumns = new ArrayList<>(); currentPkColumns.addAll(sortedParentPkColumns); currentPkColumns.addAll(sortedCurrentPkColumns); return currentPkColumns; }
Example #10
Source File: SchemaValidator.java From lams with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings("unchecked") public void validate(Metadata metadata, ServiceRegistry serviceRegistry) { LOG.runningSchemaValidator(); Map config = new HashMap(); config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() ); final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class ); final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions( config, ExceptionHandlerHaltImpl.INSTANCE ); tool.getSchemaValidator( config ).doValidation( metadata, executionOptions ); }
Example #11
Source File: SchemaCreatorImpl.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public void doCreation( Metadata metadata, ExecutionOptions options, SourceDescriptor sourceDescriptor, TargetDescriptor targetDescriptor) { if ( targetDescriptor.getTargetTypes().isEmpty() ) { return; } final JdbcContext jdbcContext = tool.resolveJdbcContext( options.getConfigurationValues() ); final GenerationTarget[] targets = tool.buildGenerationTargets( targetDescriptor, jdbcContext, options.getConfigurationValues(), true ); doCreation( metadata, jdbcContext.getDialect(), options, sourceDescriptor, targets ); }
Example #12
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); metadataSources.addAnnotatedClass(Email.class); metadataSources.addAnnotatedClass(Office.class); metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); }
Example #13
Source File: SpannerTableExporterTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void omitCreatingPreexistingTables() throws IOException, SQLException { this.connection.setMetaData(MockJdbcUtils.metaDataBuilder() .setTables("Employee") .build()); Metadata employeeMetadata = new MetadataSources(this.registry).addAnnotatedClass(Employee.class).buildMetadata(); String testFileName = UUID.randomUUID().toString(); new SchemaExport().setOutputFile(testFileName) .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), employeeMetadata); File scriptFile = new File(testFileName); scriptFile.deleteOnExit(); List<String> statements = Files.readAllLines(scriptFile.toPath()); assertThat(statements).containsExactly( // This omits creating the Employee table since it is declared to exist in metadata. "START BATCH DDL", "create table hibernate_sequence (next_val INT64) PRIMARY KEY ()", "create index name_index on Employee (name)", "alter table Employee add constraint FKiralam2duuhr33k8a10aoc2t6 " + "foreign key (manager_id) references Employee (id)", "RUN BATCH", "INSERT INTO hibernate_sequence (next_val) VALUES(1)" ); }
Example #14
Source File: SpannerTableExporterTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void generateCreateStringsNoPkEntityTest() { assertThatThrownBy(() -> { Metadata metadata = new MetadataSources(this.registry) .addAnnotatedClass(NoPkEntity.class) .buildMetadata(); new SchemaExport() .setOutputFile("unused") .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), metadata); }) .isInstanceOf(AnnotationException.class) .hasMessage( "No identifier specified for entity: " + "com.google.cloud.spanner.hibernate.SpannerTableExporterTests$NoPkEntity"); }
Example #15
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
/** * Generates database create commands for the specified entities using Hibernate native API, SchemaExport. * Creation commands are exported into the create.sql file. */ public static void generateSchema() { Map<String, String> settings = new HashMap<>(); settings.put(Environment.URL, "jdbc:h2:mem:schema"); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(Account.class); metadataSources.addAnnotatedClass(AccountSetting.class); Metadata metadata = metadataSources.buildMetadata(); SchemaExport schemaExport = new SchemaExport(); schemaExport.setFormat(true); schemaExport.setOutputFile("create.sql"); schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata); }
Example #16
Source File: HibernateLifecycleUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(FootballPlayer.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder(); }
Example #17
Source File: RedirectionSchemaInitializer.java From teiid-spring-boot with Apache License 2.0 | 5 votes |
RedirectionSchemaInitializer(DataSource dataSource, String sourceName, Dialect dialect, Metadata metadata, ServiceRegistry registry, Schema schema, ApplicationContext applicationContext) { super(dataSource, sourceName, applicationContext); this.dialect = dialect; this.metadata = metadata; this.schema = schema; this.registry = registry; }
Example #18
Source File: ModelDBHibernateUtil.java From modeldb with Apache License 2.0 | 5 votes |
private static void exportSchema(Metadata buildMetadata) { String rootPath = System.getProperty(ModelDBConstants.userDir); rootPath = rootPath + "\\src\\main\\resources\\liquibase\\hibernate-base-db-schema.sql"; new SchemaExport() .setDelimiter(";") .setOutputFile(rootPath) .create(EnumSet.of(TargetType.SCRIPT), buildMetadata); }
Example #19
Source File: HibernateUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Employee.class); metadataSources.addAnnotatedClass(Phone.class); metadataSources.addAnnotatedClass(EntityDescription.class); metadataSources.addAnnotatedClass(TemporalValues.class); metadataSources.addAnnotatedClass(User.class); metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(Course.class); metadataSources.addAnnotatedClass(Product.class); metadataSources.addAnnotatedClass(OrderEntryPK.class); metadataSources.addAnnotatedClass(OrderEntry.class); metadataSources.addAnnotatedClass(OrderEntryIdClass.class); metadataSources.addAnnotatedClass(UserProfile.class); metadataSources.addAnnotatedClass(Book.class); metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(Post.class); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); }
Example #20
Source File: DefaultPersistManager.java From onedev with MIT License | 5 votes |
@Sessional @Override public void importData(Metadata metadata, File dataDir) { Session session = dao.getSession(); List<Class<?>> entityTypes = getEntityTypes(sessionFactory); Collections.reverse(entityTypes); for (Class<?> entityType: entityTypes) { File[] dataFiles = dataDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(entityType.getSimpleName() + "s.xml"); } }); for (File file: dataFiles) { Transaction transaction = session.beginTransaction(); try { logger.info("Importing from data file '" + file.getName() + "'..."); VersionedXmlDoc dom = VersionedXmlDoc.fromFile(file); for (Element element: dom.getRootElement().elements()) { element.detach(); AbstractEntity entity = (AbstractEntity) new VersionedXmlDoc(DocumentHelper.createDocument(element)).toBean(); session.replicate(entity, ReplicationMode.EXCEPTION); } session.flush(); session.clear(); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw ExceptionUtils.unchecked(e); } } } }
Example #21
Source File: ProxyDefinitions.java From quarkus with Apache License 2.0 | 5 votes |
private static boolean needAnyProxyDefinitions(Metadata storeableMetadata) { for (PersistentClass persistentClass : storeableMetadata.getEntityBindings()) { if (needsProxyGeneration(persistentClass)) return true; } return false; }
Example #22
Source File: SchemaUpdate.java From lams with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") public void execute(EnumSet<TargetType> targetTypes, Metadata metadata, ServiceRegistry serviceRegistry) { if ( targetTypes.isEmpty() ) { LOG.debug( "Skipping SchemaExport as no targets were specified" ); return; } exceptions.clear(); LOG.runningHbm2ddlSchemaUpdate(); Map config = new HashMap(); config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() ); config.put( AvailableSettings.HBM2DDL_DELIMITER, delimiter ); config.put( AvailableSettings.FORMAT_SQL, format ); final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class ); final ExceptionHandler exceptionHandler = haltOnError ? ExceptionHandlerHaltImpl.INSTANCE : new ExceptionHandlerCollectingImpl(); final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions( config, exceptionHandler ); final TargetDescriptor targetDescriptor = SchemaExport.buildTargetDescriptor( targetTypes, outputFile, serviceRegistry ); try { tool.getSchemaMigrator( config ).doMigration( metadata, executionOptions, targetDescriptor ); } finally { if ( exceptionHandler instanceof ExceptionHandlerCollectingImpl ) { exceptions.addAll( ( (ExceptionHandlerCollectingImpl) exceptionHandler ).getExceptions() ); } } }
Example #23
Source File: HibernateAnnotationUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } }
Example #24
Source File: DefaultPersistManager.java From onedev with MIT License | 5 votes |
protected Metadata buildMetadata() { MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class<? extends AbstractEntity> each: ClassUtils.findImplementations(AbstractEntity.class, AbstractEntity.class)) { metadataSources.addAnnotatedClass(each); } MetadataBuilder builder = metadataSources.getMetadataBuilder(); builder.applyPhysicalNamingStrategy(physicalNamingStrategy); return builder.build(); }
Example #25
Source File: Settings.java From lams with GNU General Public License v2.0 | 5 votes |
public Settings(SessionFactoryOptions sessionFactoryOptions, Metadata metadata) { this( sessionFactoryOptions, extractName( metadata.getDatabase().getDefaultNamespace().getName().getCatalog() ), extractName( metadata.getDatabase().getDefaultNamespace().getName().getSchema() ) ); }
Example #26
Source File: SchemaDropperImpl.java From lams with GNU General Public License v2.0 | 5 votes |
/** * For testing... * * @param metadata The metadata for which to generate the creation commands. * * @return The generation commands */ public List<String> generateDropCommands(Metadata metadata, final boolean manageNamespaces) { final JournalingGenerationTarget target = new JournalingGenerationTarget(); final ServiceRegistry serviceRegistry = ( (MetadataImplementor) metadata ).getMetadataBuildingOptions() .getServiceRegistry(); final Dialect dialect = serviceRegistry.getService( JdbcEnvironment.class ).getDialect(); final ExecutionOptions options = new ExecutionOptions() { @Override public boolean shouldManageNamespaces() { return manageNamespaces; } @Override public Map getConfigurationValues() { return Collections.emptyMap(); } @Override public ExceptionHandler getExceptionHandler() { return ExceptionHandlerHaltImpl.INSTANCE; } }; dropFromMetadata( metadata, options, dialect, FormatStyle.NONE.getFormatter(), target ); return target.commands; }
Example #27
Source File: HibernateUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Employee.class); metadataSources.addAnnotatedClass(Phone.class); metadataSources.addAnnotatedClass(EntityDescription.class); metadataSources.addAnnotatedClass(TemporalValues.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(Animal.class); metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(Book.class); metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(MyEmployee.class); metadataSources.addAnnotatedClass(MyProduct.class); metadataSources.addAnnotatedClass(Pen.class); metadataSources.addAnnotatedClass(Pet.class); metadataSources.addAnnotatedClass(Vehicle.class); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); }
Example #28
Source File: HibernateUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); }
Example #29
Source File: AbstractSchemaMigrator.java From lams with GNU General Public License v2.0 | 5 votes |
protected void createTable( Table table, Dialect dialect, Metadata metadata, Formatter formatter, ExecutionOptions options, GenerationTarget... targets) { applySqlStrings( false, dialect.getTableExporter().getSqlCreateStrings( table, metadata ), formatter, options, targets ); }
Example #30
Source File: HibernateDatastore.java From gorm-hibernate5 with Apache License 2.0 | 5 votes |
private Metadata getMetadataInternal() { Metadata metadata = null; ServiceRegistry bootstrapServiceRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getParentServiceRegistry(); Iterable<Integrator> integrators = bootstrapServiceRegistry.getService(IntegratorService.class).getIntegrators(); for (Integrator integrator : integrators) { if (integrator instanceof MetadataIntegrator) { metadata = ((MetadataIntegrator) integrator).getMetadata(); } } return metadata; }