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

The following examples show how to use org.hibernate.boot.MetadataSources#addAnnotatedClass() . 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: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
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 2
Source File: NamingStrategyLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void init() {
    try {
        Configuration configuration = new Configuration();

        Properties properties = new Properties();
        properties.load(Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("hibernate-namingstrategy.properties"));

        configuration.setProperties(properties);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        MetadataSources metadataSources = new MetadataSources(serviceRegistry);
        metadataSources.addAnnotatedClass(Customer.class);

        SessionFactory factory = metadataSources.buildMetadata()
            .buildSessionFactory();

        session = factory.openSession();
    } catch (HibernateException | IOException e) {
        fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
    }
}
 
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: PersistJSONUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void init() {
    try {
        Configuration configuration = new Configuration();

        Properties properties = new Properties();
        properties.load(Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("hibernate-persistjson.properties"));

        configuration.setProperties(properties);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        MetadataSources metadataSources = new MetadataSources(serviceRegistry);
        metadataSources.addAnnotatedClass(Customer.class);

        SessionFactory factory = metadataSources.buildMetadata()
            .buildSessionFactory();

        session = factory.openSession();
    } catch (HibernateException | IOException e) {
        fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
    }
}
 
Example 5
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
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 6
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * 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 7
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 8
Source File: HibernateL2CacheStrategySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param accessType Cache access typr.
 * @param igniteInstanceName Name of the grid providing caches.
 * @return Session factory.
 */
private SessionFactory startHibernate(AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    builder.applySetting("hibernate.connection.url", CONNECTION_URL);

    for (Map.Entry<String, String> e : HibernateL2CacheSelfTest.hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    builder.applySetting(USE_STRUCTURED_CACHE, "true");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY1_NAME, "cache1");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, "cache2");
    builder.applySetting(REGION_CACHE_PROPERTY + TIMESTAMP_CACHE, TIMESTAMP_CACHE);
    builder.applySetting(REGION_CACHE_PROPERTY + QUERY_CACHE, QUERY_CACHE);

    MetadataSources metadataSources = new MetadataSources(builder.build());

    metadataSources.addAnnotatedClass(Entity1.class);
    metadataSources.addAnnotatedClass(Entity2.class);
    metadataSources.addAnnotatedClass(Entity3.class);
    metadataSources.addAnnotatedClass(Entity4.class);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    return metadata.buildSessionFactory();
}
 
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: HibernateSessionUtil.java    From tutorials with MIT License 5 votes vote down vote up
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addAnnotatedClass(User.class);

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

}
 
Example 11
Source File: HibernateL2CacheSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Starts Hibernate.
 *
 * @param accessType Cache access type.
 * @param igniteInstanceName Ignite instance name.
 * @return Session factory.
 */
private SessionFactory startHibernate(org.hibernate.cache.spi.access.AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = registryBuilder();

    for (Map.Entry<String, String> e : hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    // Use the same cache for Entity and Entity2.
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, ENTITY_NAME);

    StandardServiceRegistry srvcRegistry = builder.build();

    MetadataSources metadataSources = new MetadataSources(srvcRegistry);

    for (Class entityClass : getAnnotatedClasses())
        metadataSources.addAnnotatedClass(entityClass);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass) entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    for (org.hibernate.mapping.Collection collectionBinding : metadata.getCollectionBindings())
        collectionBinding.setCacheConcurrencyStrategy(accessType.getExternalName());

    return metadata.buildSessionFactory();
}
 
Example 12
Source File: HibernateUtil.java    From tutorials with MIT License 5 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        ServiceRegistry serviceRegistry = configureServiceRegistry();

        MetadataSources metadataSources = new MetadataSources(serviceRegistry);

        metadataSources.addAnnotatedClass(Student.class);
        Metadata metadata = metadataSources.getMetadataBuilder()
                .applyBasicType(LocalDateStringType.INSTANCE)
                .build();
        return metadata.getSessionFactoryBuilder().build();
    } catch (IOException ex) {
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 13
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 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: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 4 votes vote down vote up
public static SessionFactory createOrGetSessionFactory() throws ModelDBException {
  if (sessionFactory == null) {
    LOGGER.info("Fetching sessionFactory");
    try {
      App app = App.getInstance();
      Map<String, Object> databasePropMap = app.getDatabasePropMap();

      Map<String, Object> rDBPropMap =
          (Map<String, Object>) databasePropMap.get("RdbConfiguration");

      databaseName = (String) rDBPropMap.get("RdbDatabaseName");
      if (!app.getTraceEnabled()) {
        rDBDriver = (String) rDBPropMap.get("RdbDriver");
      } else {
        rDBDriver = "io.opentracing.contrib.jdbc.TracingDriver";
      }
      rDBUrl = (String) rDBPropMap.get("RdbUrl");
      rDBDialect = (String) rDBPropMap.get("RdbDialect");
      configUsername = (String) rDBPropMap.get("RdbUsername");
      configPassword = (String) rDBPropMap.get("RdbPassword");
      if (databasePropMap.containsKey("timeout")) {
        timeout = (Integer) databasePropMap.get("timeout");
      }
      liquibaseLockThreshold =
          Long.parseLong(databasePropMap.getOrDefault("liquibaseLockThreshold", "60").toString());

      // Change liquibase default table names
      System.getProperties().put("liquibase.databaseChangeLogTableName", "database_change_log");
      System.getProperties()
          .put("liquibase.databaseChangeLogLockTableName", "database_change_log_lock");

      // Hibernate settings equivalent to hibernate.cfg.xml's properties
      Configuration configuration = new Configuration();

      Properties settings = new Properties();

      String connectionString =
          rDBUrl
              + "/"
              + databaseName
              + "?createDatabaseIfNotExist=true&useUnicode=yes&characterEncoding=UTF-8";
      settings.put(Environment.DRIVER, rDBDriver);
      settings.put(Environment.URL, connectionString);
      settings.put(Environment.USER, configUsername);
      settings.put(Environment.PASS, configPassword);
      settings.put(Environment.DIALECT, rDBDialect);
      settings.put(Environment.HBM2DDL_AUTO, "validate");
      settings.put(Environment.SHOW_SQL, "false");
      configuration.setProperties(settings);

      LOGGER.trace("connectionString {}", connectionString);
      // Create registry builder
      StandardServiceRegistryBuilder registryBuilder =
          new StandardServiceRegistryBuilder().applySettings(settings);
      MetadataSources metaDataSrc = new MetadataSources(registryBuilder.build());
      for (Class entity : entities) {
        metaDataSrc.addAnnotatedClass(entity);
      }

      // Check DB is up or not
      boolean dbConnectionStatus =
          checkDBConnection(
              rDBDriver, rDBUrl, databaseName, configUsername, configPassword, timeout);
      if (!dbConnectionStatus) {
        checkDBConnectionInLoop(true);
      }

      releaseLiquibaseLock(metaDataSrc);

      // Run tables liquibase migration
      createTablesLiquibaseMigration(metaDataSrc);

      // Create session factory and validate entity
      sessionFactory = metaDataSrc.buildMetadata().buildSessionFactory();

      // Export schema
      if (ModelDBConstants.EXPORT_SCHEMA) {
        exportSchema(metaDataSrc.buildMetadata());
      }

      // Check if any migration need to be run or not and based on the migration status flag
      runMigration();

      LOGGER.info(ModelDBMessages.READY_STATUS, isReady);
      isReady = true;
      return sessionFactory;
    } catch (Exception e) {
      LOGGER.warn(
          "ModelDBHibernateUtil getSessionFactory() getting error : {}", e.getMessage(), e);
      if (registry != null) {
        StandardServiceRegistryBuilder.destroy(registry);
      }
      throw new ModelDBException(e.getMessage());
    }
  } else {
    return loopBack(sessionFactory);
  }
}
 
Example 16
Source File: HibernateL2CacheMultiJvmTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param nodeName Name of the grid providing caches.
 * @return Session factory.
 */
SessionFactory startHibernate(String nodeName) {
    log.info("Start hibernate on node: " + nodeName);

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    for (Map.Entry<String, String> e : hibernateProperties(nodeName, NONSTRICT_READ_WRITE.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    builder.applySetting("hibernate.connection.url", CONNECTION_URL);

    MetadataSources metadataSources = new MetadataSources(builder.build());

    metadataSources.addAnnotatedClass(Entity1.class);
    metadataSources.addAnnotatedClass(Entity2.class);
    metadataSources.addAnnotatedClass(Entity3.class);

    return metadataSources.buildMetadata().buildSessionFactory();
}
 
Example 17
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 18
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();
}
 
Example 19
Source File: EntityManagerFactoryBuilderImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
	protected List<AttributeConverterDefinition> populate(
			MetadataSources metadataSources,
			MergedSettings mergedSettings,
			StandardServiceRegistry ssr) {
//		final ClassLoaderService classLoaderService = ssr.getService( ClassLoaderService.class );
//
//		// todo : make sure MetadataSources/Metadata are capable of handling duplicate sources
//
//		// explicit persistence unit mapping files listings
//		if ( persistenceUnit.getMappingFileNames() != null ) {
//			for ( String name : persistenceUnit.getMappingFileNames() ) {
//				metadataSources.addResource( name );
//			}
//		}
//
//		// explicit persistence unit managed class listings
//		//		IMPL NOTE : managed-classes can contain class or package names!!!
//		if ( persistenceUnit.getManagedClassNames() != null ) {
//			for ( String managedClassName : persistenceUnit.getManagedClassNames() ) {
//				// try it as a class name first...
//				final String classFileName = managedClassName.replace( '.', '/' ) + ".class";
//				final URL classFileUrl = classLoaderService.locateResource( classFileName );
//				if ( classFileUrl != null ) {
//					// it is a class
//					metadataSources.addAnnotatedClassName( managedClassName );
//					continue;
//				}
//
//				// otherwise, try it as a package name
//				final String packageInfoFileName = managedClassName.replace( '.', '/' ) + "/package-info.class";
//				final URL packageInfoFileUrl = classLoaderService.locateResource( packageInfoFileName );
//				if ( packageInfoFileUrl != null ) {
//					// it is a package
//					metadataSources.addPackage( managedClassName );
//					continue;
//				}
//
//				LOG.debugf(
//						"Unable to resolve class [%s] named in persistence unit [%s]",
//						managedClassName,
//						persistenceUnit.getName()
//				);
//			}
//		}

		List<AttributeConverterDefinition> attributeConverterDefinitions = null;

		// add any explicit Class references passed in
		final List<Class> loadedAnnotatedClasses = (List<Class>) configurationValues.remove( AvailableSettings.LOADED_CLASSES );
		if ( loadedAnnotatedClasses != null ) {
			for ( Class cls : loadedAnnotatedClasses ) {
				if ( AttributeConverter.class.isAssignableFrom( cls ) ) {
					if ( attributeConverterDefinitions == null ) {
						attributeConverterDefinitions = new ArrayList<>();
					}
					attributeConverterDefinitions.add( AttributeConverterDefinition.from( (Class<? extends AttributeConverter>) cls ) );
				}
				else {
					metadataSources.addAnnotatedClass( cls );
				}
			}
		}

		// add any explicit hbm.xml references passed in
		final String explicitHbmXmls = (String) configurationValues.remove( AvailableSettings.HBXML_FILES );
		if ( explicitHbmXmls != null ) {
			for ( String hbmXml : StringHelper.split( ", ", explicitHbmXmls ) ) {
				metadataSources.addResource( hbmXml );
			}
		}

		// add any explicit orm.xml references passed in
		final List<String> explicitOrmXmlList = (List<String>) configurationValues.remove( AvailableSettings.XML_FILE_NAMES );
		if ( explicitOrmXmlList != null ) {
			explicitOrmXmlList.forEach( metadataSources::addResource );
		}

		return attributeConverterDefinitions;
	}
 
Example 20
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();
}