Search in sources :

Example 1 with AttributeConverter

use of javax.persistence.AttributeConverter in project hibernate-orm by hibernate.

the class ScanningCoordinator method applyScanResultsToManagedResources.

public void applyScanResultsToManagedResources(ManagedResourcesImpl managedResources, ScanResult scanResult, MetadataBuildingOptions options, XmlMappingBinderAccess xmlMappingBinderAccess) {
    final ScanEnvironment scanEnvironment = options.getScanEnvironment();
    final ServiceRegistry serviceRegistry = options.getServiceRegistry();
    final ClassLoaderService classLoaderService = serviceRegistry.getService(ClassLoaderService.class);
    // mapping files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final Set<String> nonLocatedMappingFileNames = new HashSet<String>();
    final List<String> explicitMappingFileNames = scanEnvironment.getExplicitlyListedMappingFiles();
    if (explicitMappingFileNames != null) {
        nonLocatedMappingFileNames.addAll(explicitMappingFileNames);
    }
    for (MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles()) {
        managedResources.addXmlBinding(xmlMappingBinderAccess.bind(mappingFileDescriptor.getStreamAccess()));
        nonLocatedMappingFileNames.remove(mappingFileDescriptor.getName());
    }
    for (String name : nonLocatedMappingFileNames) {
        final URL url = classLoaderService.locateResource(name);
        if (url == null) {
            throw new MappingException("Unable to resolve explicitly named mapping-file : " + name, new Origin(SourceType.RESOURCE, name));
        }
        final UrlInputStreamAccess inputStreamAccess = new UrlInputStreamAccess(url);
        managedResources.addXmlBinding(xmlMappingBinderAccess.bind(inputStreamAccess));
    }
    // classes and packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final List<String> unresolvedListedClassNames = scanEnvironment.getExplicitlyListedClassNames() == null ? new ArrayList<String>() : new ArrayList<String>(scanEnvironment.getExplicitlyListedClassNames());
    for (ClassDescriptor classDescriptor : scanResult.getLocatedClasses()) {
        if (classDescriptor.getCategorization() == ClassDescriptor.Categorization.CONVERTER) {
            // converter classes are safe to load because we never enhance them,
            // and notice we use the ClassLoaderService specifically, not the temp ClassLoader (if any)
            managedResources.addAttributeConverterDefinition(AttributeConverterDefinition.from(classLoaderService.<AttributeConverter>classForName(classDescriptor.getName())));
        } else if (classDescriptor.getCategorization() == ClassDescriptor.Categorization.MODEL) {
            managedResources.addAnnotatedClassName(classDescriptor.getName());
        }
        unresolvedListedClassNames.remove(classDescriptor.getName());
    }
    // IMPL NOTE : "explicitlyListedClassNames" can contain class or package names...
    for (PackageDescriptor packageDescriptor : scanResult.getLocatedPackages()) {
        managedResources.addAnnotatedPackageName(packageDescriptor.getName());
        unresolvedListedClassNames.remove(packageDescriptor.getName());
    }
    for (String unresolvedListedClassName : unresolvedListedClassNames) {
        // because the explicit list can contain either class names or package names
        // we need to check for both here...
        // First, try it as a class name
        final String classFileName = unresolvedListedClassName.replace('.', '/') + ".class";
        final URL classFileUrl = classLoaderService.locateResource(classFileName);
        if (classFileUrl != null) {
            managedResources.addAnnotatedClassName(unresolvedListedClassName);
            continue;
        }
        // Then, try it as a package name
        final String packageInfoFileName = unresolvedListedClassName.replace('.', '/') + "/package-info.class";
        final URL packageInfoFileUrl = classLoaderService.locateResource(packageInfoFileName);
        if (packageInfoFileUrl != null) {
            managedResources.addAnnotatedPackageName(unresolvedListedClassName);
            continue;
        }
        log.debugf("Unable to resolve class [%s] named in persistence unit [%s]", unresolvedListedClassName, scanEnvironment.getRootUrl());
    }
}
Also used : Origin(org.hibernate.boot.jaxb.Origin) MappingFileDescriptor(org.hibernate.boot.archive.scan.spi.MappingFileDescriptor) ClassDescriptor(org.hibernate.boot.archive.scan.spi.ClassDescriptor) UrlInputStreamAccess(org.hibernate.boot.archive.internal.UrlInputStreamAccess) PackageDescriptor(org.hibernate.boot.archive.scan.spi.PackageDescriptor) URL(java.net.URL) MappingException(org.hibernate.boot.MappingException) AttributeConverter(javax.persistence.AttributeConverter) ScanEnvironment(org.hibernate.boot.archive.scan.spi.ScanEnvironment) ServiceRegistry(org.hibernate.service.ServiceRegistry) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService) HashSet(java.util.HashSet)

Example 2 with AttributeConverter

use of javax.persistence.AttributeConverter in project hibernate-orm by hibernate.

the class AttributeConverterDefinition method from.

/**
	 * Build an AttributeConverterDefinition from an AttributeConverter instance.  The
	 * converter is searched for a {@link Converter} annotation	 to determine whether it should
	 * be treated as auto-apply.  If the annotation is present, {@link Converter#autoApply()} is
	 * used to make that determination.  If the annotation is not present, {@code false} is assumed.
	 *
	 * @param attributeConverter The AttributeConverter instance
	 *
	 * @return The constructed definition
	 */
public static AttributeConverterDefinition from(AttributeConverter attributeConverter) {
    boolean autoApply = false;
    Converter converterAnnotation = attributeConverter.getClass().getAnnotation(Converter.class);
    if (converterAnnotation != null) {
        autoApply = converterAnnotation.autoApply();
    }
    return new AttributeConverterDefinition(attributeConverter, autoApply);
}
Also used : AttributeConverter(javax.persistence.AttributeConverter) Converter(javax.persistence.Converter)

Example 3 with AttributeConverter

use of javax.persistence.AttributeConverter in project hibernate-orm by hibernate.

the class LiteralNode method determineConvertedValue.

@SuppressWarnings("unchecked")
protected String determineConvertedValue(AttributeConverterTypeAdapter converterTypeAdapter, Object literalValue) {
    if (getDataType().getReturnedClass().equals(converterTypeAdapter.getModelType())) {
        // apply the converter
        final AttributeConverter converter = converterTypeAdapter.getAttributeConverter();
        final Object converted = converter.convertToDatabaseColumn(getLiteralValue());
        if (isCharacterData(converterTypeAdapter.sqlType())) {
            return "'" + converted.toString() + "'";
        } else {
            return converted.toString();
        }
    } else if (getDataType().getReturnedClass().equals(converterTypeAdapter.getJdbcType())) {
        if (isCharacterData(converterTypeAdapter.sqlType())) {
            return "'" + literalValue.toString() + "'";
        } else {
            return literalValue.toString();
        }
    } else {
        throw new QueryException(String.format(Locale.ROOT, "AttributeConverter domain-model attribute type [%s] and JDBC type [%s] did not match query literal type [%s]", converterTypeAdapter.getModelType().getName(), converterTypeAdapter.getJdbcType().getName(), getDataType().getReturnedClass().getName()));
    }
}
Also used : AttributeConverter(javax.persistence.AttributeConverter) QueryException(org.hibernate.QueryException)

Example 4 with AttributeConverter

use of javax.persistence.AttributeConverter in project hibernate-orm by hibernate.

the class EntityManagerFactoryBuilderImpl method populate.

@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) {
        for (String ormXml : explicitOrmXmlList) {
            metadataSources.addResource(ormXml);
        }
    }
    return attributeConverterDefinitions;
}
Also used : AttributeConverter(javax.persistence.AttributeConverter) AttributeConverterDefinition(org.hibernate.cfg.AttributeConverterDefinition) ArrayList(java.util.ArrayList) StrategyRegistrationProviderList(org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList) List(java.util.List) TypeContributorList(org.hibernate.jpa.boot.spi.TypeContributorList) UnloadedClass(org.hibernate.bytecode.enhance.spi.UnloadedClass)

Example 5 with AttributeConverter

use of javax.persistence.AttributeConverter in project hibernate-orm by hibernate.

the class AttributeConverterDescriptorImpl method create.

public static AttributeConverterDescriptor create(AttributeConverterDefinition definition, ClassmateContext classmateContext) {
    final AttributeConverter converter = definition.getAttributeConverter();
    final Class converterClass = converter.getClass();
    final ResolvedType converterType = classmateContext.getTypeResolver().resolve(converterClass);
    final List<ResolvedType> converterParamTypes = converterType.typeParametersFor(AttributeConverter.class);
    if (converterParamTypes == null) {
        throw new AnnotationException("Could not extract type parameter information from AttributeConverter implementation [" + converterClass.getName() + "]");
    } else if (converterParamTypes.size() != 2) {
        throw new AnnotationException("Unexpected type parameter information for AttributeConverter implementation [" + converterClass.getName() + "]; expected 2 parameter types, but found " + converterParamTypes.size());
    }
    return new AttributeConverterDescriptorImpl(converter, definition.isAutoApply(), converterParamTypes.get(0), converterParamTypes.get(1));
}
Also used : AttributeConverter(javax.persistence.AttributeConverter) AnnotationException(org.hibernate.AnnotationException) ResolvedType(com.fasterxml.classmate.ResolvedType)

Aggregations

AttributeConverter (javax.persistence.AttributeConverter)6 ClassLoaderService (org.hibernate.boot.registry.classloading.spi.ClassLoaderService)2 ResolvedType (com.fasterxml.classmate.ResolvedType)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Converter (javax.persistence.Converter)1 AnnotationException (org.hibernate.AnnotationException)1 MappingException (org.hibernate.MappingException)1 QueryException (org.hibernate.QueryException)1 MappingException (org.hibernate.boot.MappingException)1 UrlInputStreamAccess (org.hibernate.boot.archive.internal.UrlInputStreamAccess)1 ClassDescriptor (org.hibernate.boot.archive.scan.spi.ClassDescriptor)1 MappingFileDescriptor (org.hibernate.boot.archive.scan.spi.MappingFileDescriptor)1 PackageDescriptor (org.hibernate.boot.archive.scan.spi.PackageDescriptor)1 ScanEnvironment (org.hibernate.boot.archive.scan.spi.ScanEnvironment)1 AttributeConverterDescriptorNonAutoApplicableImpl (org.hibernate.boot.internal.AttributeConverterDescriptorNonAutoApplicableImpl)1 Origin (org.hibernate.boot.jaxb.Origin)1 ClassLoadingException (org.hibernate.boot.registry.classloading.spi.ClassLoadingException)1