Search in sources :

Example 91 with MappingException

use of org.hibernate.MappingException in project hibernate-orm by hibernate.

the class BackquoteTest method testInvalidReferenceToQuotedTableName.

/**
	 *  HHH-4647 : Problems with @JoinColumn referencedColumnName and quoted column and table names
	 *
	 *  An invalid referencedColumnName to an entity having a quoted table name results in an
	 *  infinite loop in o.h.c.Configuration$MappingsImpl#getPhysicalColumnName().
	 *  The same issue exists with getLogicalColumnName()
	 */
@Test
@TestForIssue(jiraKey = "HHH-4647")
public void testInvalidReferenceToQuotedTableName() {
    try {
        Configuration config = new Configuration();
        config.addAnnotatedClass(Printer.class);
        config.addAnnotatedClass(PrinterCable.class);
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        fail("expected MappingException to be thrown");
    }//we WANT MappingException to be thrown
     catch (MappingException e) {
        assertTrue("MappingException was thrown", true);
    } catch (Exception e) {
        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer));
        log.debug(writer.toString());
        fail(e.getMessage());
    } finally {
        if (sessionFactory != null) {
            sessionFactory.close();
            sessionFactory = null;
        }
    }
}
Also used : Configuration(org.hibernate.cfg.Configuration) StringWriter(java.io.StringWriter) MappingException(org.hibernate.MappingException) MappingException(org.hibernate.MappingException) PrintWriter(java.io.PrintWriter) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 92 with MappingException

use of org.hibernate.MappingException in project hibernate-orm by hibernate.

the class PersisterClassProviderTest method testPersisterClassProvider.

@Test
public void testPersisterClassProvider() throws Exception {
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(Gate.class);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
    //no exception as the GoofyPersisterClassProvider is not set
    SessionFactory sessionFactory;
    try {
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        sessionFactory.close();
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).addService(PersisterClassResolver.class, new GoofyPersisterClassProvider()).build();
    cfg = new Configuration();
    cfg.addAnnotatedClass(Gate.class);
    try {
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        sessionFactory.close();
        fail("The entity persister should be overridden");
    } catch (MappingException e) {
        assertEquals("The entity persister should be overridden", GoofyPersisterClassProvider.NoopEntityPersister.class, ((GoofyException) e.getCause()).getValue());
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
    assertFalse(SessionFactoryRegistry.INSTANCE.hasRegistrations());
    cfg = new Configuration();
    cfg.addAnnotatedClass(Portal.class);
    cfg.addAnnotatedClass(Window.class);
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).addService(PersisterClassResolver.class, new GoofyPersisterClassProvider()).build();
    try {
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        sessionFactory.close();
        fail("The collection persister should be overridden but not the entity persister");
    } catch (MappingException e) {
        assertEquals("The collection persister should be overridden but not the entity persister", GoofyPersisterClassProvider.NoopCollectionPersister.class, ((GoofyException) e.getCause()).getValue());
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
    cfg = new Configuration();
    cfg.addAnnotatedClass(Tree.class);
    cfg.addAnnotatedClass(Palmtree.class);
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).addService(PersisterClassResolver.class, new GoofyPersisterClassProvider()).build();
    try {
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        sessionFactory.close();
        fail("The entity persisters should be overridden in a class hierarchy");
    } catch (MappingException e) {
        assertEquals("The entity persisters should be overridden in a class hierarchy", GoofyPersisterClassProvider.NoopEntityPersister.class, ((GoofyException) e.getCause()).getValue());
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
    assertFalse(SessionFactoryRegistry.INSTANCE.hasRegistrations());
}
Also used : SessionFactory(org.hibernate.SessionFactory) Configuration(org.hibernate.cfg.Configuration) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) ServiceRegistry(org.hibernate.service.ServiceRegistry) MappingException(org.hibernate.MappingException) Test(org.junit.Test)

Example 93 with MappingException

use of org.hibernate.MappingException in project querydsl by querydsl.

the class HibernateDomainExporter method handleProperty.

private void handleProperty(EntityType entityType, Class<?> cl, org.hibernate.mapping.Property p) throws NoSuchMethodException, ClassNotFoundException {
    if (p.isBackRef()) {
        return;
    }
    Class<?> clazz = Object.class;
    try {
        clazz = p.getType().getReturnedClass();
    } catch (MappingException e) {
    // ignore
    }
    Type propertyType = getType(cl, clazz, p.getName());
    try {
        propertyType = getPropertyType(p, propertyType);
    } catch (MappingException e) {
    // ignore
    }
    AnnotatedElement annotated = getAnnotatedElement(cl, p.getName());
    propertyType = getTypeOverride(propertyType, annotated);
    if (propertyType == null) {
        return;
    }
    if (p.isComposite()) {
        EntityType embeddedType = createEmbeddableType(propertyType);
        Iterator<?> properties = ((Component) p.getValue()).getPropertyIterator();
        while (properties.hasNext()) {
            handleProperty(embeddedType, embeddedType.getJavaClass(), (org.hibernate.mapping.Property) properties.next());
        }
        propertyType = embeddedType;
    } else if (propertyType.getCategory() == TypeCategory.ENTITY || p.getValue() instanceof ManyToOne) {
        propertyType = createEntityType(propertyType);
    } else if (propertyType.getCategory() == TypeCategory.CUSTOM) {
        propertyType = createEmbeddableType(propertyType);
    } else if (p.getValue() instanceof org.hibernate.mapping.Collection) {
        org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) p.getValue();
        if (collection.getElement() instanceof OneToMany) {
            String entityName = ((OneToMany) collection.getElement()).getReferencedEntityName();
            if (entityName != null) {
                if (collection.isMap()) {
                    Type keyType = typeFactory.get(Class.forName(propertyType.getParameters().get(0).getFullName()));
                    Type valueType = typeFactory.get(Class.forName(entityName));
                    propertyType = new SimpleType(propertyType, normalize(propertyType.getParameters().get(0), keyType), normalize(propertyType.getParameters().get(1), valueType));
                } else {
                    Type componentType = typeFactory.get(Class.forName(entityName));
                    propertyType = new SimpleType(propertyType, normalize(propertyType.getParameters().get(0), componentType));
                }
            }
        } else if (collection.getElement() instanceof Component) {
            Component component = (Component) collection.getElement();
            Class<?> embeddedClass = Class.forName(component.getComponentClassName());
            EntityType embeddedType = createEmbeddableType(embeddedClass);
            Iterator<?> properties = component.getPropertyIterator();
            while (properties.hasNext()) {
                handleProperty(embeddedType, embeddedClass, (org.hibernate.mapping.Property) properties.next());
            }
        }
    }
    Property property = createProperty(entityType, p.getName(), propertyType, annotated);
    entityType.addProperty(property);
}
Also used : org.hibernate.mapping(org.hibernate.mapping) AnnotatedElement(java.lang.reflect.AnnotatedElement) MappingException(org.hibernate.MappingException) EntityType(com.querydsl.codegen.EntityType) SimpleType(com.mysema.codegen.model.SimpleType) Type(com.mysema.codegen.model.Type) EntityType(com.querydsl.codegen.EntityType) SimpleType(com.mysema.codegen.model.SimpleType) Property(com.querydsl.codegen.Property)

Example 94 with MappingException

use of org.hibernate.MappingException in project spring-framework by spring-projects.

the class LocalSessionFactoryBuilder method scanPackages.

/**
	 * Perform Spring-based scanning for entity classes, registering them
	 * as annotated classes with this {@code Configuration}.
	 * @param packagesToScan one or more Java package names
	 * @throws HibernateException if scanning fails for any reason
	 */
@SuppressWarnings("unchecked")
public LocalSessionFactoryBuilder scanPackages(String... packagesToScan) throws HibernateException {
    Set<String> entityClassNames = new TreeSet<>();
    Set<String> converterClassNames = new TreeSet<>();
    Set<String> packageNames = new TreeSet<>();
    try {
        for (String pkg : packagesToScan) {
            String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN;
            Resource[] resources = this.resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader reader = readerFactory.getMetadataReader(resource);
                    String className = reader.getClassMetadata().getClassName();
                    if (matchesEntityTypeFilter(reader, readerFactory)) {
                        entityClassNames.add(className);
                    } else if (CONVERTER_TYPE_FILTER.match(reader, readerFactory)) {
                        converterClassNames.add(className);
                    } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                        packageNames.add(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                    }
                }
            }
        }
    } catch (IOException ex) {
        throw new MappingException("Failed to scan classpath for unlisted classes", ex);
    }
    try {
        ClassLoader cl = this.resourcePatternResolver.getClassLoader();
        for (String className : entityClassNames) {
            addAnnotatedClass(cl.loadClass(className));
        }
        for (String className : converterClassNames) {
            addAttributeConverter((Class<? extends AttributeConverter<?, ?>>) cl.loadClass(className));
        }
        for (String packageName : packageNames) {
            addPackage(packageName);
        }
    } catch (ClassNotFoundException ex) {
        throw new MappingException("Failed to load annotated classes from classpath", ex);
    }
    return this;
}
Also used : CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) MetadataReaderFactory(org.springframework.core.type.classreading.MetadataReaderFactory) TreeSet(java.util.TreeSet) Resource(org.springframework.core.io.Resource) MetadataReader(org.springframework.core.type.classreading.MetadataReader) CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) IOException(java.io.IOException) MappingException(org.hibernate.MappingException)

Aggregations

MappingException (org.hibernate.MappingException)94 PersistentClass (org.hibernate.mapping.PersistentClass)17 HibernateException (org.hibernate.HibernateException)12 Iterator (java.util.Iterator)11 Test (org.junit.Test)11 AnnotationException (org.hibernate.AnnotationException)10 QueryException (org.hibernate.QueryException)10 Type (org.hibernate.type.Type)10 Property (org.hibernate.mapping.Property)9 HashMap (java.util.HashMap)8 XClass (org.hibernate.annotations.common.reflection.XClass)8 DuplicateMappingException (org.hibernate.DuplicateMappingException)6 Configuration (org.hibernate.cfg.Configuration)6 UnknownSqlResultSetMappingException (org.hibernate.procedure.UnknownSqlResultSetMappingException)6 ServiceRegistry (org.hibernate.service.ServiceRegistry)6 Map (java.util.Map)5 AssociationType (org.hibernate.type.AssociationType)5 HashSet (java.util.HashSet)4 ClassLoadingException (org.hibernate.annotations.common.reflection.ClassLoadingException)4 MetadataSources (org.hibernate.boot.MetadataSources)4