use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.
the class BinderHelper method buildAnyValue.
public static Any buildAnyValue(String anyMetaDefName, Ejb3JoinColumn[] columns, javax.persistence.Column metaColumn, PropertyData inferredData, boolean cascadeOnDelete, Nullability nullability, PropertyHolder propertyHolder, EntityBinder entityBinder, boolean optional, MetadataBuildingContext context) {
// All FK columns should be in the same table
Any value = new Any(context, columns[0].getTable());
AnyMetaDef metaAnnDef = inferredData.getProperty().getAnnotation(AnyMetaDef.class);
if (metaAnnDef != null) {
// local has precedence over general and can be mapped for future reference if named
bindAnyMetaDefs(inferredData.getProperty(), context);
} else {
metaAnnDef = context.getMetadataCollector().getAnyMetaDef(anyMetaDefName);
}
if (metaAnnDef != null) {
value.setIdentifierType(metaAnnDef.idType());
value.setMetaType(metaAnnDef.metaType());
HashMap values = new HashMap();
org.hibernate.type.Type metaType = context.getMetadataCollector().getTypeResolver().heuristicType(value.getMetaType());
for (MetaValue metaValue : metaAnnDef.metaValues()) {
try {
Object discrim = ((org.hibernate.type.DiscriminatorType) metaType).stringToObject(metaValue.value());
String entityName = metaValue.targetEntity().getName();
values.put(discrim, entityName);
} catch (ClassCastException cce) {
throw new MappingException("metaType was not a DiscriminatorType: " + metaType.getName());
} catch (Exception e) {
throw new MappingException("could not interpret metaValue", e);
}
}
if (!values.isEmpty()) {
value.setMetaValues(values);
}
} else {
throw new AnnotationException("Unable to find @AnyMetaDef for an @(ManyTo)Any mapping: " + StringHelper.qualify(propertyHolder.getPath(), inferredData.getPropertyName()));
}
value.setCascadeDeleteEnabled(cascadeOnDelete);
if (!optional) {
for (Ejb3JoinColumn column : columns) {
column.setNullable(false);
}
}
Ejb3Column[] metaColumns = Ejb3Column.buildColumnFromAnnotation(new javax.persistence.Column[] { metaColumn }, null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), context);
// set metaColumn to the right table
for (Ejb3Column column : metaColumns) {
column.setTable(value.getTable());
}
// meta column
for (Ejb3Column column : metaColumns) {
column.linkWithValue(value);
}
// id columns
final String propertyName = inferredData.getPropertyName();
Ejb3Column.checkPropertyConsistency(columns, propertyHolder.getEntityName() + "." + propertyName);
for (Ejb3JoinColumn column : columns) {
column.linkWithValue(value);
}
return value;
}
use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.
the class BinderHelper method makeIdGenerator.
/**
* apply an id generator to a SimpleValue
*/
public static void makeIdGenerator(SimpleValue id, XProperty idXProperty, String generatorType, String generatorName, MetadataBuildingContext buildingContext, Map<String, IdentifierGeneratorDefinition> localGenerators) {
log.debugf("#makeIdGenerator(%s, %s, %s, %s, ...)", id, idXProperty, generatorType, generatorName);
Table table = id.getTable();
table.setIdentifierValue(id);
// generator settings
id.setIdentifierGeneratorStrategy(generatorType);
Properties params = new Properties();
// always settable
params.setProperty(PersistentIdentifierGenerator.TABLE, table.getName());
final String implicitCatalogName = buildingContext.getBuildingOptions().getMappingDefaults().getImplicitCatalogName();
if (implicitCatalogName != null) {
params.put(PersistentIdentifierGenerator.CATALOG, implicitCatalogName);
}
final String implicitSchemaName = buildingContext.getBuildingOptions().getMappingDefaults().getImplicitSchemaName();
if (implicitSchemaName != null) {
params.put(PersistentIdentifierGenerator.SCHEMA, implicitSchemaName);
}
if (id.getColumnSpan() == 1) {
params.setProperty(PersistentIdentifierGenerator.PK, ((org.hibernate.mapping.Column) id.getColumnIterator().next()).getName());
}
// YUCK! but cannot think of a clean way to do this given the string-config based scheme
params.put(PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER, buildingContext.getObjectNameNormalizer());
params.put(IdentifierGenerator.GENERATOR_NAME, generatorName);
if (!isEmptyAnnotationValue(generatorName)) {
// we have a named generator
IdentifierGeneratorDefinition gen = getIdentifierGenerator(generatorName, idXProperty, localGenerators, buildingContext);
if (gen == null) {
throw new AnnotationException("Unknown named generator (@GeneratedValue#generatorName): " + generatorName);
}
// This is quite vague in the spec but a generator could override the generate choice
String identifierGeneratorStrategy = gen.getStrategy();
// yuk! this is a hack not to override 'AUTO' even if generator is set
final boolean avoidOverriding = identifierGeneratorStrategy.equals("identity") || identifierGeneratorStrategy.equals("seqhilo") || identifierGeneratorStrategy.equals(MultipleHiLoPerTableGenerator.class.getName());
if (generatorType == null || !avoidOverriding) {
id.setIdentifierGeneratorStrategy(identifierGeneratorStrategy);
}
// checkIfMatchingGenerator(gen, generatorType, generatorName);
for (Object o : gen.getParameters().entrySet()) {
Map.Entry elt = (Map.Entry) o;
if (elt.getKey() == null) {
continue;
}
params.setProperty((String) elt.getKey(), (String) elt.getValue());
}
}
if ("assigned".equals(generatorType)) {
id.setNullValue("undefined");
}
id.setIdentifierGeneratorProperties(params);
}
use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.
the class SimpleValueBinder method fillSimpleValue.
public void fillSimpleValue() {
LOG.debugf("Starting fillSimpleValue for %s", propertyName);
if (attributeConverterDescriptor != null) {
if (!BinderHelper.isEmptyAnnotationValue(explicitType)) {
throw new AnnotationException(String.format("AttributeConverter and explicit Type cannot be applied to same attribute [%s.%s];" + "remove @Type or specify @Convert(disableConversion = true)", persistentClassName, propertyName));
}
LOG.debugf("Applying JPA AttributeConverter [%s] to [%s:%s]", attributeConverterDescriptor, persistentClassName, propertyName);
simpleValue.setJpaAttributeConverterDescriptor(attributeConverterDescriptor);
} else {
String type;
TypeDefinition typeDef;
if (!BinderHelper.isEmptyAnnotationValue(explicitType)) {
type = explicitType;
typeDef = buildingContext.getMetadataCollector().getTypeDefinition(type);
} else {
// try implicit type
TypeDefinition implicitTypeDef = buildingContext.getMetadataCollector().getTypeDefinition(returnedClassName);
if (implicitTypeDef != null) {
typeDef = implicitTypeDef;
type = returnedClassName;
} else {
typeDef = buildingContext.getMetadataCollector().getTypeDefinition(defaultType);
type = defaultType;
}
}
if (typeDef != null) {
type = typeDef.getTypeImplementorClass().getName();
simpleValue.setTypeParameters(typeDef.getParametersAsProperties());
}
if (typeParameters != null && typeParameters.size() != 0) {
// explicit type params takes precedence over type def params
simpleValue.setTypeParameters(typeParameters);
}
simpleValue.setTypeName(type);
}
if (persistentClassName != null || attributeConverterDescriptor != null) {
try {
simpleValue.setTypeUsingReflection(persistentClassName, propertyName);
} catch (Exception e) {
throw new MappingException(String.format(Locale.ROOT, "Unable to determine basic type mapping via reflection [%s -> %s]", persistentClassName, propertyName), e);
}
}
if (!simpleValue.isTypeSpecified() && isVersion()) {
simpleValue.setTypeName("integer");
}
// HHH-5205
if (timeStampVersionType != null) {
simpleValue.setTypeName(timeStampVersionType);
}
if (simpleValue.getTypeName() != null && simpleValue.getTypeName().length() > 0 && simpleValue.getMetadata().getTypeResolver().basic(simpleValue.getTypeName()) == null) {
try {
Class typeClass = buildingContext.getBootstrapContext().getClassLoaderAccess().classForName(simpleValue.getTypeName());
if (typeClass != null && DynamicParameterizedType.class.isAssignableFrom(typeClass)) {
Properties parameters = simpleValue.getTypeParameters();
if (parameters == null) {
parameters = new Properties();
}
parameters.put(DynamicParameterizedType.IS_DYNAMIC, Boolean.toString(true));
parameters.put(DynamicParameterizedType.RETURNED_CLASS, returnedClassName);
parameters.put(DynamicParameterizedType.IS_PRIMARY_KEY, Boolean.toString(key));
parameters.put(DynamicParameterizedType.ENTITY, persistentClassName);
parameters.put(DynamicParameterizedType.XPROPERTY, xproperty);
parameters.put(DynamicParameterizedType.PROPERTY, xproperty.getName());
parameters.put(DynamicParameterizedType.ACCESS_TYPE, accessType.getType());
simpleValue.setTypeParameters(parameters);
}
} catch (ClassLoadingException e) {
throw new MappingException("Could not determine type for: " + simpleValue.getTypeName(), e);
}
}
}
use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.
the class SimpleValueBinder method setType.
// TODO execute it lazily to be order safe
public void setType(XProperty property, XClass returnedClass, String declaringClassName, ConverterDescriptor attributeConverterDescriptor) {
if (returnedClass == null) {
// we cannot guess anything
return;
}
XClass returnedClassOrElement = returnedClass;
boolean isArray = false;
if (property.isArray()) {
returnedClassOrElement = property.getElementClass();
isArray = true;
}
this.xproperty = property;
Properties typeParameters = this.typeParameters;
typeParameters.clear();
String type = BinderHelper.ANNOTATION_STRING_DEFAULT;
if (getDialect().supportsNationalizedTypes()) {
isNationalized = property.isAnnotationPresent(Nationalized.class) || buildingContext.getBuildingOptions().useNationalizedCharacterData();
}
Type annType = null;
if ((!key && property.isAnnotationPresent(Type.class)) || (key && property.isAnnotationPresent(MapKeyType.class))) {
if (key) {
MapKeyType ann = property.getAnnotation(MapKeyType.class);
annType = ann.value();
} else {
annType = property.getAnnotation(Type.class);
}
}
if (annType != null) {
setExplicitType(annType);
type = explicitType;
} else if ((!key && property.isAnnotationPresent(Temporal.class)) || (key && property.isAnnotationPresent(MapKeyTemporal.class))) {
boolean isDate;
if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Date.class)) {
isDate = true;
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Calendar.class)) {
isDate = false;
} else {
throw new AnnotationException("@Temporal should only be set on a java.util.Date or java.util.Calendar property: " + StringHelper.qualify(persistentClassName, propertyName));
}
final TemporalType temporalType = getTemporalType(property);
switch(temporalType) {
case DATE:
type = isDate ? "date" : "calendar_date";
break;
case TIME:
type = "time";
if (!isDate) {
throw new NotYetImplementedException("Calendar cannot persist TIME only" + StringHelper.qualify(persistentClassName, propertyName));
}
break;
case TIMESTAMP:
type = isDate ? "timestamp" : "calendar";
break;
default:
throw new AssertionFailure("Unknown temporal type: " + temporalType);
}
explicitType = type;
} else if (!key && property.isAnnotationPresent(Lob.class)) {
isLob = true;
if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, java.sql.Clob.class)) {
type = isNationalized ? StandardBasicTypes.NCLOB.getName() : StandardBasicTypes.CLOB.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, java.sql.NClob.class)) {
type = StandardBasicTypes.NCLOB.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, java.sql.Blob.class)) {
type = "blob";
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, String.class)) {
type = isNationalized ? StandardBasicTypes.MATERIALIZED_NCLOB.getName() : StandardBasicTypes.MATERIALIZED_CLOB.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Character.class) && isArray) {
type = isNationalized ? CharacterArrayNClobType.class.getName() : CharacterArrayClobType.class.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, char.class) && isArray) {
type = isNationalized ? PrimitiveCharacterArrayNClobType.class.getName() : PrimitiveCharacterArrayClobType.class.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Byte.class) && isArray) {
type = WrappedMaterializedBlobType.class.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, byte.class) && isArray) {
type = StandardBasicTypes.MATERIALIZED_BLOB.getName();
} else if (buildingContext.getBootstrapContext().getReflectionManager().toXClass(Serializable.class).isAssignableFrom(returnedClassOrElement)) {
type = SerializableToBlobType.class.getName();
typeParameters.setProperty(SerializableToBlobType.CLASS_NAME, returnedClassOrElement.getName());
} else {
type = "blob";
}
defaultType = type;
} else if ((!key && property.isAnnotationPresent(Enumerated.class)) || (key && property.isAnnotationPresent(MapKeyEnumerated.class))) {
final Class attributeJavaType = buildingContext.getBootstrapContext().getReflectionManager().toClass(returnedClassOrElement);
if (!Enum.class.isAssignableFrom(attributeJavaType)) {
throw new AnnotationException(String.format("Attribute [%s.%s] was annotated as enumerated, but its java type is not an enum [%s]", declaringClassName, xproperty.getName(), attributeJavaType.getName()));
}
type = EnumType.class.getName();
explicitType = type;
} else if (isNationalized) {
if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, String.class)) {
// nvarchar
type = StringNVarcharType.INSTANCE.getName();
explicitType = type;
} else if (buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, Character.class) || buildingContext.getBootstrapContext().getReflectionManager().equals(returnedClassOrElement, char.class)) {
if (isArray) {
// nvarchar
type = StringNVarcharType.INSTANCE.getName();
} else {
// nchar
type = CharacterNCharType.INSTANCE.getName();
}
explicitType = type;
}
}
// implicit type will check basic types and Serializable classes
if (columns == null) {
throw new AssertionFailure("SimpleValueBinder.setColumns should be set before SimpleValueBinder.setType");
}
if (BinderHelper.ANNOTATION_STRING_DEFAULT.equals(type)) {
if (returnedClassOrElement.isEnum()) {
type = EnumType.class.getName();
}
}
defaultType = BinderHelper.isEmptyAnnotationValue(type) ? returnedClassName : type;
this.typeParameters = typeParameters;
applyAttributeConverter(property, attributeConverterDescriptor);
}
use of org.hibernate.AnnotationException in project hibernate-orm by hibernate.
the class OneToOneSecondPass method doSecondPass.
// TODO refactor this code, there is a lot of duplication in this method
public void doSecondPass(Map persistentClasses) throws MappingException {
org.hibernate.mapping.OneToOne value = new org.hibernate.mapping.OneToOne(buildingContext, propertyHolder.getTable(), propertyHolder.getPersistentClass());
final String propertyName = inferredData.getPropertyName();
value.setPropertyName(propertyName);
String referencedEntityName = ToOneBinder.getReferenceEntityName(inferredData, targetEntity, buildingContext);
value.setReferencedEntityName(referencedEntityName);
AnnotationBinder.defineFetchingStrategy(value, inferredData.getProperty());
// value.setFetchMode( fetchMode );
value.setCascadeDeleteEnabled(cascadeOnDelete);
if (!optional) {
value.setConstrained(true);
}
if (value.isReferenceToPrimaryKey()) {
value.setForeignKeyType(ForeignKeyDirection.TO_PARENT);
} else {
value.setForeignKeyType(value.isConstrained() ? ForeignKeyDirection.FROM_PARENT : ForeignKeyDirection.TO_PARENT);
}
PropertyBinder binder = new PropertyBinder();
binder.setName(propertyName);
binder.setValue(value);
binder.setCascade(cascadeStrategy);
binder.setAccessType(inferredData.getDefaultAccess());
final LazyGroup lazyGroupAnnotation = inferredData.getProperty().getAnnotation(LazyGroup.class);
if (lazyGroupAnnotation != null) {
binder.setLazyGroup(lazyGroupAnnotation.value());
}
Property prop = binder.makeProperty();
prop.setOptional(optional);
if (BinderHelper.isEmptyAnnotationValue(mappedBy)) {
/*
* we need to check if the columns are in the right order
* if not, then we need to create a many to one and formula
* but actually, since entities linked by a one to one need
* to share the same composite id class, this cannot happen in hibernate
*/
boolean rightOrder = true;
if (rightOrder) {
String path = StringHelper.qualify(propertyHolder.getPath(), propertyName);
final ToOneFkSecondPass secondPass = new ToOneFkSecondPass(value, joinColumns, // cannot have nullabe and unique on certain DBs
!optional, propertyHolder.getEntityOwnerClassName(), path, buildingContext);
secondPass.doSecondPass(persistentClasses);
// no column associated since its a one to one
propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
} else {
// this is a many to one with Formula
}
} else {
PersistentClass otherSide = (PersistentClass) persistentClasses.get(value.getReferencedEntityName());
Property otherSideProperty;
try {
if (otherSide == null) {
throw new MappingException("Unable to find entity: " + value.getReferencedEntityName());
}
otherSideProperty = BinderHelper.findPropertyByName(otherSide, mappedBy);
} catch (MappingException e) {
throw new AnnotationException("Unknown mappedBy in: " + StringHelper.qualify(ownerEntity, ownerProperty) + ", referenced property unknown: " + StringHelper.qualify(value.getReferencedEntityName(), mappedBy));
}
if (otherSideProperty == null) {
throw new AnnotationException("Unknown mappedBy in: " + StringHelper.qualify(ownerEntity, ownerProperty) + ", referenced property unknown: " + StringHelper.qualify(value.getReferencedEntityName(), mappedBy));
}
if (otherSideProperty.getValue() instanceof OneToOne) {
propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
} else if (otherSideProperty.getValue() instanceof ManyToOne) {
Iterator it = otherSide.getJoinIterator();
Join otherSideJoin = null;
while (it.hasNext()) {
Join otherSideJoinValue = (Join) it.next();
if (otherSideJoinValue.containsProperty(otherSideProperty)) {
otherSideJoin = otherSideJoinValue;
break;
}
}
if (otherSideJoin != null) {
// @OneToOne @JoinTable
Join mappedByJoin = buildJoinFromMappedBySide((PersistentClass) persistentClasses.get(ownerEntity), otherSideProperty, otherSideJoin);
ManyToOne manyToOne = new ManyToOne(buildingContext, mappedByJoin.getTable());
// FIXME use ignore not found here
manyToOne.setIgnoreNotFound(ignoreNotFound);
manyToOne.setCascadeDeleteEnabled(value.isCascadeDeleteEnabled());
manyToOne.setFetchMode(value.getFetchMode());
manyToOne.setLazy(value.isLazy());
manyToOne.setReferencedEntityName(value.getReferencedEntityName());
manyToOne.setUnwrapProxy(value.isUnwrapProxy());
prop.setValue(manyToOne);
Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator();
while (otherSideJoinKeyColumns.hasNext()) {
Column column = (Column) otherSideJoinKeyColumns.next();
Column copy = new Column();
copy.setLength(column.getLength());
copy.setScale(column.getScale());
copy.setValue(manyToOne);
copy.setName(column.getQuotedName());
copy.setNullable(column.isNullable());
copy.setPrecision(column.getPrecision());
copy.setUnique(column.isUnique());
copy.setSqlType(column.getSqlType());
copy.setCheckConstraint(column.getCheckConstraint());
copy.setComment(column.getComment());
copy.setDefaultValue(column.getDefaultValue());
manyToOne.addColumn(copy);
}
mappedByJoin.addProperty(prop);
} else {
propertyHolder.addProperty(prop, inferredData.getDeclaringClass());
}
value.setReferencedPropertyName(mappedBy);
// HHH-6813
// Foo: @Id long id, @OneToOne(mappedBy="foo") Bar bar
// Bar: @Id @OneToOne Foo foo
boolean referencesDerivedId = false;
try {
referencesDerivedId = otherSide.getIdentifier() instanceof Component && ((Component) otherSide.getIdentifier()).getProperty(mappedBy) != null;
} catch (MappingException e) {
// ignore
}
boolean referenceToPrimaryKey = referencesDerivedId || mappedBy == null;
value.setReferenceToPrimaryKey(referenceToPrimaryKey);
// loop of attempts to resolve identifiers.
if (referencesDerivedId) {
((ManyToOne) otherSideProperty.getValue()).setReferenceToPrimaryKey(false);
}
String propertyRef = value.getReferencedPropertyName();
if (propertyRef != null) {
buildingContext.getMetadataCollector().addUniquePropertyReference(value.getReferencedEntityName(), propertyRef);
}
} else {
throw new AnnotationException("Referenced property not a (One|Many)ToOne: " + StringHelper.qualify(otherSide.getEntityName(), mappedBy) + " in mappedBy of " + StringHelper.qualify(ownerEntity, ownerProperty));
}
}
final ForeignKey fk = inferredData.getProperty().getAnnotation(ForeignKey.class);
if (fk != null && !BinderHelper.isEmptyAnnotationValue(fk.name())) {
value.setForeignKeyName(fk.name());
} else {
final javax.persistence.ForeignKey jpaFk = inferredData.getProperty().getAnnotation(javax.persistence.ForeignKey.class);
if (jpaFk != null) {
if (jpaFk.value() == ConstraintMode.NO_CONSTRAINT) {
value.setForeignKeyName("none");
} else {
value.setForeignKeyName(StringHelper.nullIfEmpty(jpaFk.name()));
value.setForeignKeyDefinition(StringHelper.nullIfEmpty(jpaFk.foreignKeyDefinition()));
}
}
}
}
Aggregations