Java Code Examples for org.hibernate.boot.Metadata#getEntityBindings()

The following examples show how to use org.hibernate.boot.Metadata#getEntityBindings() . 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: MetadataTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityToDatabaseBindingMetadata() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
        Table table = persistentClass.getTable();
        LOGGER.info( "Entity: {} is mapped to table: {}",
                     persistentClass.getClassName(),
                     table.getName()
        );

        for(Iterator propertyIterator =
                persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
            Property property = (Property) propertyIterator.next();
            for(Iterator columnIterator =
                    property.getColumnIterator(); columnIterator.hasNext(); ) {
                Column column = (Column) columnIterator.next();
                LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
                             property.getName(),
                             column.getName(),
                             column.getSqlType()
                );
            }
        }
    }
}
 
Example 2
Source File: SchemaUtils.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the {@link Interleaved} annotation on a table if it exists.
 */
public static Interleaved getInterleaveAnnotation(Table table, Metadata metadata) {
  for (PersistentClass pc : metadata.getEntityBindings()) {
    if (pc.getTable().equals(table) && pc.getMappedClass() != null) {
      Class<?> entityClass = pc.getMappedClass();
      return entityClass.getAnnotation(Interleaved.class);
    }
  }

  return null;
}
 
Example 3
Source File: ProxyDefinitions.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static ProxyDefinitions createFromMetadata(Metadata storeableMetadata, PreGeneratedProxies preGeneratedProxies) {
    //Check upfront for any need across all metadata: would be nice to avoid initializing the Bytecode provider.
    LazyBytecode lazyBytecode = new LazyBytecode();
    if (needAnyProxyDefinitions(storeableMetadata)) {
        final HashMap<Class<?>, ProxyClassDetailsHolder> proxyDefinitionMap = new HashMap<>();
        try {
            for (PersistentClass persistentClass : storeableMetadata.getEntityBindings()) {
                if (needsProxyGeneration(persistentClass)) {
                    final Class mappedClass = persistentClass.getMappedClass();
                    final Class proxyClassDefinition = generateProxyClass(persistentClass, lazyBytecode,
                            preGeneratedProxies);
                    if (proxyClassDefinition == null) {
                        continue;
                    }
                    final boolean overridesEquals = ReflectHelper.overridesEquals(mappedClass);
                    try {
                        proxyDefinitionMap.put(mappedClass,
                                new ProxyClassDetailsHolder(overridesEquals, proxyClassDefinition.getConstructor()));
                    } catch (NoSuchMethodException e) {
                        throw new HibernateException(
                                "Failed to generate Enhanced Proxy: default constructor is missing for entity '"
                                        + mappedClass.getName() + "'. Please add a default constructor explicitly.");
                    }
                }
            }
        } finally {
            lazyBytecode.close();
        }
        return new ProxyDefinitions(proxyDefinitionMap);
    } else {
        return new ProxyDefinitions(Collections.emptyMap());
    }
}
 
Example 4
Source File: ProxyDefinitions.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static boolean needAnyProxyDefinitions(Metadata storeableMetadata) {
    for (PersistentClass persistentClass : storeableMetadata.getEntityBindings()) {
        if (needsProxyGeneration(persistentClass))
            return true;
    }
    return false;
}
 
Example 5
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 6
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 7
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 + DEFAULT_UPDATE_TIMESTAMPS_REGION_UNQUALIFIED_NAME, DEFAULT_UPDATE_TIMESTAMPS_REGION_UNQUALIFIED_NAME);
    builder.applySetting(REGION_CACHE_PROPERTY + DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME, DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME);

    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 8
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 9
Source File: EventIntegrator.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {
    EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService(EventListenerRegistry.class);

    Collection<PersistentClass> entityBindings = metadata.getEntityBindings();
    Map<Class, BeanProperty> lastUpdates = new HashMap<>(entityBindings.size());
    Map<Class, BeanProperty> dateCreated = new HashMap<>(entityBindings.size());

    entityBindings.forEach(e -> {
                Class<?> mappedClass = e.getMappedClass();
                if (mappedClass != null) {
                    BeanIntrospection<?> introspection = BeanIntrospector.SHARED.findIntrospection(mappedClass).orElse(null);
                    if (introspection != null) {
                        introspection.getIndexedProperty(DateCreated.class).ifPresent(bp ->
                                dateCreated.put(mappedClass, bp)
                        );
                        introspection.getIndexedProperty(DateUpdated.class).ifPresent(bp ->
                                lastUpdates.put(mappedClass, bp)
                        );
                    }
                }
            }
    );

    ConversionService<?> conversionService = ConversionService.SHARED;

    if (CollectionUtils.isNotEmpty(dateCreated)) {

        eventListenerRegistry.getEventListenerGroup(EventType.PRE_INSERT)
                .appendListener((PreInsertEventListener) event -> {
                    Object[] state = event.getState();
                    timestampIfNecessary(
                            dateCreated,
                            lastUpdates,
                            conversionService,
                            event,
                            state,
                            true
                    );
                    return false;
                });
    }

    if (CollectionUtils.isNotEmpty(lastUpdates)) {

        eventListenerRegistry.getEventListenerGroup(EventType.PRE_UPDATE)
                .appendListener((PreUpdateEventListener) event -> {
                    timestampIfNecessary(
                            dateCreated, lastUpdates,
                            conversionService,
                            event,
                            event.getState(),
                            false
                    );
                    return false;
                });
    }
}