Java Code Examples for org.hibernate.boot.MetadataSources#addPackage()

The following examples show how to use org.hibernate.boot.MetadataSources#addPackage() . 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: MappingReference.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void apply(MetadataSources metadataSources) {
	switch ( getType() ) {
		case RESOURCE: {
			metadataSources.addResource( getReference() );
			break;
		}
		case CLASS: {
			metadataSources.addAnnotatedClassName( getReference() );
			break;
		}
		case FILE: {
			metadataSources.addFile( getReference() );
			break;
		}
		case PACKAGE: {
			metadataSources.addPackage( getReference() );
			break;
		}
		case JAR: {
			metadataSources.addJar( new File( getReference() ) );
			break;
		}
	}
}
 
Example 2
Source File: DbInitializer.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * 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 3
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);

    metadataSources.addPackage("com.baeldung.hibernate.pojo");
    metadataSources.addAnnotatedClass(Student.class);
    metadataSources.addAnnotatedClass(DeptEmployee.class);
    metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);

    Metadata metadata = metadataSources.getMetadataBuilder()
            .applyBasicType(LocalDateStringType.INSTANCE)
            .build();

    return metadata.getSessionFactoryBuilder()
            .build();

}
 
Example 4
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
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 5
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);

    metadataSources.addPackage("com.baeldung.hibernate.pojo");
    metadataSources.addAnnotatedClass(Person.class);
    metadataSources.addAnnotatedClass(Student.class);
    metadataSources.addAnnotatedClass(Individual.class);
    metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
    metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
    metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
    metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
    metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
    metadataSources.addAnnotatedClass(DeptEmployee.class);
    metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
    metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
    metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
    metadataSources.addAnnotatedClass(Post.class);

    Metadata metadata = metadataSources.getMetadataBuilder()
            .build();

    return metadata.getSessionFactoryBuilder()
            .build();

}
 
Example 6
Source File: HibernateUtil.java    From tutorials with MIT License 5 votes vote down vote up
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 7
Source File: HibernateUtil.java    From tutorials with MIT License 5 votes vote down vote up
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 8
Source File: HibernateUtil.java    From tutorials with MIT License 5 votes vote down vote up
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addPackage("com.baeldung.hibernate.proxy");
    metadataSources.addAnnotatedClass(Company.class);
    metadataSources.addAnnotatedClass(Employee.class);

    Metadata metadata = metadataSources.buildMetadata();
    return metadata.getSessionFactoryBuilder();

}
 
Example 9
Source File: HibernateUtil.java    From tutorials with MIT License 5 votes vote down vote up
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 10
Source File: HibernateUtil.java    From tutorials with MIT License 5 votes vote down vote up
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addPackage("com.baeldung.hibernate.interceptors");
    metadataSources.addAnnotatedClass(User.class);

    Metadata metadata = metadataSources.buildMetadata();
    return metadata.getSessionFactoryBuilder();

}
 
Example 11
Source File: AbstractTest.java    From hypersistence-optimizer with Apache License 2.0 4 votes vote down vote up
private SessionFactory newSessionFactory() {
    final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
        .enableAutoClose();

    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);

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

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        sfb.applyInterceptor(interceptor);
    }

    return sfb.build();
}
 
Example 12
Source File: SchemaGenerator.java    From jpa2ddl with Apache License 2.0 4 votes vote down vote up
void generate(GeneratorSettings settings) throws Exception {
	validateSettings(settings);

	if (settings.getJpaProperties().getProperty(HIBERNATE_DIALECT) == null) {
		settings.getJpaProperties().setProperty(HIBERNATE_DIALECT, "org.hibernate.dialect.H2Dialect");
	}

	if (settings.isSkipSequences() && settings.getJpaProperties().getProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER) == null) {
		settings.getJpaProperties().setProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER, NoSequenceFilterProvider.class.getCanonicalName());
	}

	File outputFile = settings.getOutputPath();

	EngineDecorator engineDecorator = EngineDecorator.getEngineDecorator(settings.getJpaProperties().getProperty(HIBERNATE_DIALECT));

	if (settings.getGenerationMode() == GenerationMode.DATABASE) {

		String dbUrl = engineDecorator.decorateConnectionString(DB_URL);

		if (settings.getAction() == Action.UPDATE) {
			outputFile = FileResolver.resolveNextMigrationFile(settings.getOutputPath());
		}

		settings.getJpaProperties().setProperty("hibernate.connection.url", dbUrl);
		settings.getJpaProperties().setProperty("hibernate.connection.username", "sa");
		settings.getJpaProperties().setProperty("hibernate.connection.password", "");
		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.action", settings.getAction().toSchemaGenerationAction());

		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.create-target", outputFile.getAbsolutePath());
		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.drop-target", outputFile.getAbsolutePath());

		settings.getJpaProperties().setProperty("hibernate.hbm2ddl.delimiter", settings.getDelimiter());
		settings.getJpaProperties().setProperty("hibernate.format_sql", String.valueOf(settings.isFormatOutput()));
	}

	MetadataSources metadata = new MetadataSources(
			new StandardServiceRegistryBuilder()
					.applySettings(settings.getJpaProperties())
					.build());

	for (String packageName: settings.getPackages().stream().sorted().collect(Collectors.toList())) {
		FileResolver.listClassNamesInPackage(packageName).stream().sorted().forEach(metadata::addAnnotatedClassName);
		metadata.addPackage(packageName);
	}

	if (settings.getAction() != Action.UPDATE) {
		Files.deleteIfExists(settings.getOutputPath().toPath());
	}

	if (settings.getGenerationMode() == GenerationMode.METADATA) {
		SchemaExport export = new SchemaExport();
		export.setFormat(settings.isFormatOutput());
		export.setDelimiter(settings.getDelimiter());
		export.setOutputFile(outputFile.getAbsolutePath());
		export.execute(EnumSet.of(TargetType.SCRIPT), settings.getAction().toSchemaExportAction(), metadata.buildMetadata());
	} else {
		Connection connection = null;
		if (settings.getAction() == Action.UPDATE) {
			connection = DriverManager.getConnection(DB_URL, "SA", "");

			engineDecorator.decorateDatabaseInitialization(connection);

			List<Path> resolvedMigrations = FileResolver.resolveExistingMigrations(settings.getOutputPath(), false, true);
			for (Path resolvedMigration : resolvedMigrations) {
				String statement = new String(Files.readAllBytes(resolvedMigration));
				connection.prepareStatement(statement).execute();
			}
		}

		metadata.buildMetadata().buildSessionFactory().close();

		if (connection != null) {
			connection.close();
		}
	}

	if (outputFile.exists()) {
		if (outputFile.length() == 0) {
			Files.delete(outputFile.toPath());
		} else {
			List<String> lines = Files.readAllLines(outputFile.toPath())
					.stream()
					.map(line -> line.replaceAll("(?i)JPA2DDL\\.(PUBLIC\\.)?", ""))
					.collect(Collectors.toList());
			Files.write(outputFile.toPath(), lines);
		}
	}
}
 
Example 13
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 14
Source File: AbstractTest.java    From hibernate-types with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 15
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 4 votes vote down vote up
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()
    .enableNewIdentifierGeneratorSupport(true)
    .applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        additionalTypes.stream().forEach(type -> {
            metadataBuilder.applyTypes((typeContributions, sr) -> {
                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);
                }
            });
        });
    }

    additionalMetadata(metadataBuilder);

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

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    Interceptor interceptor = interceptor();
    if(interceptor != null) {
        sfb.applyInterceptor(interceptor);
    }

    return sfb.build();
}