use of javax.persistence.GeneratedValue in project invesdwin-context-persistence by subes.
the class MySqlLoadDataInfile method skipColumn.
private boolean skipColumn(final String javaColumnName) {
/*
* autoincrement values should be skipped in the import:
* http://stackoverflow.com/questions/14083709/mysql-load-data-infile-auto-incremented-id-value
*/
if (IEntity.class.isAssignableFrom(genericType) && IEntity.ID_COLUMN_NAME.equals(javaColumnName)) {
final Field field = Reflections.findField(genericType, javaColumnName);
final GeneratedValue annotation = Reflections.getAnnotation(field, GeneratedValue.class);
if (annotation.strategy() == GenerationType.IDENTITY || annotation.strategy() == GenerationType.AUTO) {
return true;
}
}
return false;
}
use of javax.persistence.GeneratedValue in project hibernate-orm by hibernate.
the class AnnotationBinder method fillComponent.
public static Component fillComponent(PropertyHolder propertyHolder, PropertyData inferredData, // base inferred data correspond to the entity reproducing inferredData's properties (ie IdClass)
PropertyData baseInferredData, AccessType propertyAccessor, boolean isNullable, EntityBinder entityBinder, boolean isComponentEmbedded, boolean isIdentifierMapper, boolean inSecondPass, MetadataBuildingContext buildingContext, Map<XClass, InheritanceState> inheritanceStatePerClass) {
/**
* inSecondPass can only be used to apply right away the second pass of a composite-element
* Because it's a value type, there is no bidirectional association, hence second pass
* ordering does not matter
*/
Component comp = createComponent(propertyHolder, inferredData, isComponentEmbedded, isIdentifierMapper, buildingContext);
String subpath = BinderHelper.getPath(propertyHolder, inferredData);
LOG.tracev("Binding component with path: {0}", subpath);
PropertyHolder subHolder = PropertyHolderBuilder.buildPropertyHolder(comp, subpath, inferredData, propertyHolder, buildingContext);
// propertyHolder here is the owner of the component property. Tell it we are about to start the component...
propertyHolder.startingProperty(inferredData.getProperty());
final XClass xClassProcessed = inferredData.getPropertyClass();
List<PropertyData> classElements = new ArrayList<>();
XClass returnedClassOrElement = inferredData.getClassOrElement();
List<PropertyData> baseClassElements = null;
Map<String, PropertyData> orderedBaseClassElements = new HashMap<>();
XClass baseReturnedClassOrElement;
if (baseInferredData != null) {
baseClassElements = new ArrayList<>();
baseReturnedClassOrElement = baseInferredData.getClassOrElement();
bindTypeDefs(baseReturnedClassOrElement, buildingContext);
// might be spread across the subclasses and super classes.
while (!Object.class.getName().equals(baseReturnedClassOrElement.getName())) {
PropertyContainer propContainer = new PropertyContainer(baseReturnedClassOrElement, xClassProcessed, propertyAccessor);
addElementsOfClass(baseClassElements, propContainer, buildingContext);
for (PropertyData element : baseClassElements) {
orderedBaseClassElements.put(element.getPropertyName(), element);
}
baseReturnedClassOrElement = baseReturnedClassOrElement.getSuperclass();
}
}
// embeddable elements can have type defs
bindTypeDefs(returnedClassOrElement, buildingContext);
PropertyContainer propContainer = new PropertyContainer(returnedClassOrElement, xClassProcessed, propertyAccessor);
addElementsOfClass(classElements, propContainer, buildingContext);
// add elements of the embeddable superclass
XClass superClass = xClassProcessed.getSuperclass();
while (superClass != null && superClass.isAnnotationPresent(MappedSuperclass.class)) {
// FIXME: proper support of typevariables incl var resolved at upper levels
propContainer = new PropertyContainer(superClass, xClassProcessed, propertyAccessor);
addElementsOfClass(classElements, propContainer, buildingContext);
superClass = superClass.getSuperclass();
}
if (baseClassElements != null) {
// useful to avoid breaking pre JPA 2 mappings
if (!hasAnnotationsOnIdClass(xClassProcessed)) {
for (int i = 0; i < classElements.size(); i++) {
final PropertyData idClassPropertyData = classElements.get(i);
final PropertyData entityPropertyData = orderedBaseClassElements.get(idClassPropertyData.getPropertyName());
if (propertyHolder.isInIdClass()) {
if (entityPropertyData == null) {
throw new AnnotationException("Property of @IdClass not found in entity " + baseInferredData.getPropertyClass().getName() + ": " + idClassPropertyData.getPropertyName());
}
final boolean hasXToOneAnnotation = entityPropertyData.getProperty().isAnnotationPresent(ManyToOne.class) || entityPropertyData.getProperty().isAnnotationPresent(OneToOne.class);
final boolean isOfDifferentType = !entityPropertyData.getClassOrElement().equals(idClassPropertyData.getClassOrElement());
if (hasXToOneAnnotation && isOfDifferentType) {
// don't replace here as we need to use the actual original return type
// the annotation overriding will be dealt with by a mechanism similar to @MapsId
} else {
// this works since they are in the same order
classElements.set(i, entityPropertyData);
}
} else {
// this works since they are in the same order
classElements.set(i, entityPropertyData);
}
}
}
}
for (PropertyData propertyAnnotatedElement : classElements) {
processElementAnnotations(subHolder, isNullable ? Nullability.NO_CONSTRAINT : Nullability.FORCED_NOT_NULL, propertyAnnotatedElement, new HashMap<>(), entityBinder, isIdentifierMapper, isComponentEmbedded, inSecondPass, buildingContext, inheritanceStatePerClass);
XProperty property = propertyAnnotatedElement.getProperty();
if (property.isAnnotationPresent(GeneratedValue.class) && property.isAnnotationPresent(Id.class)) {
// clone classGenerator and override with local values
// Map<String, IdentifierGeneratorDefinition> localGenerators = new HashMap<>();
// localGenerators.putAll( buildGenerators( property, buildingContext ) );
buildGenerators(property, buildingContext);
GeneratedValue generatedValue = property.getAnnotation(GeneratedValue.class);
String generatorType = generatedValue != null ? generatorType(generatedValue, buildingContext, property.getType()) : "assigned";
String generator = generatedValue != null ? generatedValue.generator() : BinderHelper.ANNOTATION_STRING_DEFAULT;
SecondPass secondPass = new IdGeneratorResolverSecondPass((SimpleValue) comp.getProperty(property.getName()).getValue(), property, generatorType, generator, buildingContext);
buildingContext.getMetadataCollector().addSecondPass(secondPass);
}
}
return comp;
}
use of javax.persistence.GeneratedValue in project hibernate-orm by hibernate.
the class BinderHelper method getIdentifierGenerator.
private static IdentifierGeneratorDefinition getIdentifierGenerator(String name, XProperty idXProperty, Map<String, IdentifierGeneratorDefinition> localGenerators, MetadataBuildingContext buildingContext) {
if (localGenerators != null) {
final IdentifierGeneratorDefinition result = localGenerators.get(name);
if (result != null) {
return result;
}
}
final IdentifierGeneratorDefinition globalDefinition = buildingContext.getMetadataCollector().getIdentifierGenerator(name);
if (globalDefinition != null) {
return globalDefinition;
}
log.debugf("Could not resolve explicit IdentifierGeneratorDefinition - using implicit interpretation (%s)", name);
// If we were unable to locate an actual matching named generator assume a sequence/table of the given name.
// this really needs access to the `javax.persistence.GenerationType` to work completely properly
//
// (the crux of HHH-12122)
// temporarily, in lieu of having access to GenerationType, assume the EnhancedSequenceGenerator
// for the purpose of testing the feasibility of the approach
final GeneratedValue generatedValueAnn = idXProperty.getAnnotation(GeneratedValue.class);
if (generatedValueAnn == null) {
// this should really never happen, but its easy to protect against it...
return new IdentifierGeneratorDefinition("assigned", "assigned");
}
final IdGeneratorStrategyInterpreter generationInterpreter = buildingContext.getBuildingOptions().getIdGenerationTypeInterpreter();
final GenerationType generationType = interpretGenerationType(generatedValueAnn);
if (generationType == null || generationType == GenerationType.SEQUENCE) {
// NOTE : `null` will ultimately be interpreted as "hibernate_sequence"
log.debugf("Building implicit sequence-based IdentifierGeneratorDefinition (%s)", name);
final IdentifierGeneratorDefinition.Builder builder = new IdentifierGeneratorDefinition.Builder();
generationInterpreter.interpretSequenceGenerator(new SequenceGenerator() {
@Override
public String name() {
return name;
}
@Override
public String sequenceName() {
return "";
}
@Override
public String catalog() {
return "";
}
@Override
public String schema() {
return "";
}
@Override
public int initialValue() {
return 1;
}
@Override
public int allocationSize() {
return 50;
}
@Override
public Class<? extends Annotation> annotationType() {
return SequenceGenerator.class;
}
}, builder);
return builder.build();
} else if (generationType == GenerationType.TABLE) {
// NOTE : `null` will ultimately be interpreted as "hibernate_sequence"
log.debugf("Building implicit table-based IdentifierGeneratorDefinition (%s)", name);
final IdentifierGeneratorDefinition.Builder builder = new IdentifierGeneratorDefinition.Builder();
generationInterpreter.interpretTableGenerator(new TableGenerator() {
@Override
public String name() {
return name;
}
@Override
public String table() {
return "";
}
@Override
public int initialValue() {
return 0;
}
@Override
public int allocationSize() {
return 50;
}
@Override
public String catalog() {
return "";
}
@Override
public String schema() {
return "";
}
@Override
public String pkColumnName() {
return "";
}
@Override
public String valueColumnName() {
return "";
}
@Override
public String pkColumnValue() {
return "";
}
@Override
public UniqueConstraint[] uniqueConstraints() {
return new UniqueConstraint[0];
}
@Override
public Index[] indexes() {
return new Index[0];
}
@Override
public Class<? extends Annotation> annotationType() {
return TableGenerator.class;
}
}, builder);
return builder.build();
}
// really AUTO and IDENTITY work the same in this respect, aside from the actual strategy name
final String strategyName;
if (generationType == GenerationType.IDENTITY) {
strategyName = "identity";
} else {
strategyName = generationInterpreter.determineGeneratorName(generationType, new IdGeneratorStrategyInterpreter.GeneratorNameDeterminationContext() {
@Override
public Class getIdType() {
return buildingContext.getBootstrapContext().getReflectionManager().toClass(idXProperty.getType());
}
@Override
public String getGeneratedValueGeneratorName() {
return generatedValueAnn.generator();
}
});
}
log.debugf("Building implicit generic IdentifierGeneratorDefinition (%s) : %s", name, strategyName);
return new IdentifierGeneratorDefinition(name, strategyName, Collections.singletonMap(IdentifierGenerator.GENERATOR_NAME, name));
}
use of javax.persistence.GeneratedValue in project requery by requery.
the class AttributeMember method processBasicColumnAnnotations.
private void processBasicColumnAnnotations(ElementValidator validator) {
if (annotationOf(Key.class).isPresent() || annotationOf(javax.persistence.Id.class).isPresent()) {
isKey = true;
if (isTransient) {
validator.error("Key field cannot be transient");
}
}
// generated keys can't be set through a setter
if (annotationOf(Generated.class).isPresent() || annotationOf(GeneratedValue.class).isPresent()) {
isGenerated = true;
isReadOnly = true;
// check generation strategy
annotationOf(GeneratedValue.class).ifPresent(generatedValue -> {
if (generatedValue.strategy() != GenerationType.IDENTITY && generatedValue.strategy() != GenerationType.AUTO) {
validator.warning("GeneratedValue.strategy() " + generatedValue.strategy() + " not supported", generatedValue.getClass());
}
});
}
if (annotationOf(Lazy.class).isPresent()) {
if (isKey) {
cannotCombine(validator, Key.class, Lazy.class);
}
isLazy = true;
}
if (annotationOf(Nullable.class).isPresent() || isOptional || Mirrors.findAnnotationMirror(element(), "javax.annotation.Nullable").isPresent()) {
isNullable = true;
} else {
// if not a primitive type the value assumed nullable
if (element().getKind().isField()) {
isNullable = !element().asType().getKind().isPrimitive();
} else if (element().getKind() == ElementKind.METHOD) {
ExecutableElement executableElement = (ExecutableElement) element();
isNullable = !executableElement.getReturnType().getKind().isPrimitive();
}
}
if (annotationOf(Version.class).isPresent() || annotationOf(javax.persistence.Version.class).isPresent()) {
isVersion = true;
if (isKey) {
cannotCombine(validator, Key.class, Version.class);
}
}
Column column = annotationOf(Column.class).orElse(null);
ForeignKey foreignKey = null;
boolean foreignKeySetFromColumn = false;
if (column != null) {
name = "".equals(column.name()) ? null : column.name();
isUnique = column.unique();
isNullable = column.nullable();
defaultValue = column.value();
collate = column.collate();
definition = column.definition();
if (column.length() > 0) {
length = column.length();
}
if (column.foreignKey().length > 0) {
foreignKey = column.foreignKey()[0];
foreignKeySetFromColumn = true;
}
}
if (!foreignKeySetFromColumn) {
foreignKey = annotationOf(ForeignKey.class).orElse(null);
}
if (foreignKey != null) {
this.isForeignKey = true;
deleteAction = foreignKey.delete();
updateAction = foreignKey.update();
referencedColumn = foreignKey.referencedColumn();
}
annotationOf(Index.class).ifPresent(index -> {
isIndexed = true;
Collections.addAll(indexNames, index.value());
});
// JPA specific
annotationOf(Basic.class).ifPresent(basic -> {
isNullable = basic.optional();
isLazy = basic.fetch() == FetchType.LAZY;
});
annotationOf(javax.persistence.Index.class).ifPresent(index -> {
isIndexed = true;
Collections.addAll(indexNames, index.name());
});
annotationOf(JoinColumn.class).ifPresent(joinColumn -> {
javax.persistence.ForeignKey joinForeignKey = joinColumn.foreignKey();
this.isForeignKey = true;
ConstraintMode constraintMode = joinForeignKey.value();
switch(constraintMode) {
default:
case PROVIDER_DEFAULT:
case CONSTRAINT:
deleteAction = ReferentialAction.CASCADE;
updateAction = ReferentialAction.CASCADE;
break;
case NO_CONSTRAINT:
deleteAction = ReferentialAction.NO_ACTION;
updateAction = ReferentialAction.NO_ACTION;
break;
}
this.referencedTable = joinColumn.table();
this.referencedColumn = joinColumn.referencedColumnName();
});
annotationOf(javax.persistence.Column.class).ifPresent(persistenceColumn -> {
name = "".equals(persistenceColumn.name()) ? null : persistenceColumn.name();
isUnique = persistenceColumn.unique();
isNullable = persistenceColumn.nullable();
length = persistenceColumn.length();
isReadOnly = !persistenceColumn.updatable();
definition = persistenceColumn.columnDefinition();
});
annotationOf(Enumerated.class).ifPresent(enumerated -> {
EnumType enumType = enumerated.value();
if (enumType == EnumType.ORDINAL) {
converterType = EnumOrdinalConverter.class.getCanonicalName();
}
});
}
use of javax.persistence.GeneratedValue in project cloudstack by apache.
the class Attribute method setupColumnInfo.
protected void setupColumnInfo(Class<?> clazz, AttributeOverride[] overrides, String tableName, boolean isEmbedded, boolean isId) {
flags = Flag.Selectable.setTrue(flags);
GeneratedValue gv = field.getAnnotation(GeneratedValue.class);
if (gv != null) {
if (gv.strategy() == GenerationType.IDENTITY) {
flags = Flag.DbGenerated.setTrue(flags);
} else if (gv.strategy() == GenerationType.SEQUENCE) {
assert (false) : "Sequence generation not supported.";
flags = Flag.DaoGenerated.setTrue(flags);
flags = Flag.Insertable.setTrue(flags);
flags = Flag.SequenceGV.setTrue(flags);
} else if (gv.strategy() == GenerationType.TABLE) {
flags = Flag.DaoGenerated.setTrue(flags);
flags = Flag.Insertable.setTrue(flags);
flags = Flag.TableGV.setTrue(flags);
} else if (gv.strategy() == GenerationType.AUTO) {
flags = Flag.DaoGenerated.setTrue(flags);
flags = Flag.Insertable.setTrue(flags);
flags = Flag.AutoGV.setTrue(flags);
}
}
if (isEmbedded) {
flags = Flag.Embedded.setTrue(flags);
}
if (isId) {
flags = Flag.Id.setTrue(flags);
} else {
Id id = field.getAnnotation(Id.class);
if (id != null) {
flags = Flag.Id.setTrue(flags);
}
}
column = field.getAnnotation(Column.class);
if (gv == null) {
if (column == null || (column.insertable() && column.table().length() == 0)) {
flags = Flag.Insertable.setTrue(flags);
}
if (column == null || (column.updatable() && column.table().length() == 0)) {
flags = Flag.Updatable.setTrue(flags);
}
if (column == null || column.nullable()) {
flags = Flag.Nullable.setTrue(flags);
}
Encrypt encrypt = field.getAnnotation(Encrypt.class);
if (encrypt != null && encrypt.encrypt()) {
flags = Flag.Encrypted.setTrue(flags);
}
}
ElementCollection ec = field.getAnnotation(ElementCollection.class);
if (ec != null) {
flags = Flag.Insertable.setFalse(flags);
flags = Flag.Selectable.setFalse(flags);
}
Temporal temporal = field.getAnnotation(Temporal.class);
if (temporal != null) {
if (temporal.value() == TemporalType.DATE) {
flags = Flag.Date.setTrue(flags);
} else if (temporal.value() == TemporalType.TIME) {
flags = Flag.Time.setTrue(flags);
} else if (temporal.value() == TemporalType.TIMESTAMP) {
flags = Flag.TimeStamp.setTrue(flags);
}
}
if (column != null && column.table().length() > 0) {
table = column.table();
}
columnName = DbUtil.getColumnName(field, overrides);
}
Aggregations