use of org.datanucleus.metadata.InheritanceMetaData in project datanucleus-rdbms by datanucleus.
the class EmbeddedMapping method initialize.
/**
* Initialize for the specified member.
* @param mmd metadata for the embedded member
* @param table Table for persisting this field
* @param clr The ClassLoaderResolver
* @param emd Embedded MetaData for the object being embedded
* @param typeName type of the embedded PC object being stored
* @param objectType Object type of the PC object being embedded (see StateManagerImpl object types)
*/
public void initialize(AbstractMemberMetaData mmd, Table table, ClassLoaderResolver clr, EmbeddedMetaData emd, String typeName, int objectType) {
super.initialize(mmd, table, clr);
this.clr = clr;
this.emd = emd;
this.typeName = typeName;
this.objectType = (short) objectType;
// Find the MetaData for the embedded PC class
MetaDataManager mmgr = table.getStoreManager().getMetaDataManager();
AbstractClassMetaData rootEmbCmd = mmgr.getMetaDataForClass(typeName, clr);
if (rootEmbCmd == null) {
// Not found so must be an interface
// Try using the fieldTypes on the field/property - we support it if only 1 implementation
String[] fieldTypes = mmd.getFieldTypes();
if (fieldTypes != null && fieldTypes.length == 1) {
rootEmbCmd = mmgr.getMetaDataForClass(fieldTypes[0], clr);
} else if (fieldTypes != null && fieldTypes.length > 1) {
// TODO Cater for multiple implementations
throw new NucleusUserException("Field " + mmd.getFullFieldName() + " is a reference field that is embedded with multiple possible implementations. " + "DataNucleus doesnt support embedded reference fields that have more than 1 implementation");
}
if (rootEmbCmd == null) {
// Try a persistent interface
rootEmbCmd = mmgr.getMetaDataForInterface(clr.classForName(typeName), clr);
if (rootEmbCmd == null && mmd.getFieldTypes() != null && mmd.getFieldTypes().length == 1) {
// No MetaData for the type so try "fieldType" specified on the field
rootEmbCmd = mmgr.getMetaDataForInterface(clr.classForName(mmd.getFieldTypes()[0]), clr);
}
}
}
if (rootEmbCmd == null) {
throw new NucleusUserException("Unable to find root class embedded metadata for field=" + mmd.getFullFieldName());
}
embCmd = rootEmbCmd;
AbstractMemberMetaData[] embFmds = null;
if (emd == null && rootEmbCmd.isEmbeddedOnly()) {
// No <embedded> block yet the class is defined as embedded-only so just use its own definition of fields
embFmds = rootEmbCmd.getManagedMembers();
} else if (emd != null) {
// <embedded> block so use those field definitions
embFmds = emd.getMemberMetaData();
}
String[] subclasses = mmgr.getSubclassesForClass(rootEmbCmd.getFullClassName(), true);
if (subclasses != null && subclasses.length > 0) {
if (rootEmbCmd.hasDiscriminatorStrategy()) {
// Fabricate a DiscriminatorMetaData to use for the embedded object
discrimMetaData = new DiscriminatorMetaData();
InheritanceMetaData embInhMd = new InheritanceMetaData();
embInhMd.setParent(rootEmbCmd);
discrimMetaData.setParent(embInhMd);
// Set strategy based on the inheritance of the embedded object, otherwise class name.
DiscriminatorMetaData dismd = rootEmbCmd.getDiscriminatorMetaDataRoot();
if (dismd.getStrategy() != null && dismd.getStrategy() != DiscriminatorStrategy.NONE) {
discrimMetaData.setStrategy(dismd.getStrategy());
} else {
// Fallback to class name
discrimMetaData.setStrategy(DiscriminatorStrategy.CLASS_NAME);
}
// Set column for discriminator
ColumnMetaData disColmd = new ColumnMetaData();
disColmd.setAllowsNull(Boolean.TRUE);
DiscriminatorMetaData embDismd = (emd != null) ? emd.getDiscriminatorMetaData() : null;
if (embDismd != null && embDismd.getColumnMetaData() != null) {
disColmd.setName(embDismd.getColumnMetaData().getName());
} else {
ColumnMetaData colmd = dismd.getColumnMetaData();
if (colmd != null && colmd.getName() != null) {
disColmd.setName(colmd.getName());
}
}
discrimMetaData.setColumnMetaData(disColmd);
discrimMapping = DiscriminatorMapping.createDiscriminatorMapping(table, discrimMetaData);
addDatastoreMapping(discrimMapping.getDatastoreMapping(0));
} else {
NucleusLogger.PERSISTENCE.info("Member " + mmd.getFullFieldName() + " is embedded and the type " + "(" + rootEmbCmd.getFullClassName() + ") has potential subclasses." + " Impossible to detect which is stored embedded. Add a discriminator to the embedded type");
}
}
// Add all fields of the embedded class (that are persistent)
int[] pcFieldNumbers = rootEmbCmd.getAllMemberPositions();
for (int i = 0; i < pcFieldNumbers.length; i++) {
AbstractMemberMetaData rootEmbMmd = rootEmbCmd.getMetaDataForManagedMemberAtAbsolutePosition(pcFieldNumbers[i]);
if (rootEmbMmd.getPersistenceModifier() == FieldPersistenceModifier.PERSISTENT) {
addMappingForMember(rootEmbCmd, rootEmbMmd, embFmds);
}
}
// Add fields for any subtypes (that are persistent)
if (discrimMapping != null && subclasses != null && subclasses.length > 0) {
for (int i = 0; i < subclasses.length; i++) {
AbstractClassMetaData subEmbCmd = storeMgr.getMetaDataManager().getMetaDataForClass(subclasses[i], clr);
AbstractMemberMetaData[] subEmbMmds = subEmbCmd.getManagedMembers();
if (subEmbMmds != null) {
for (int j = 0; j < subEmbMmds.length; j++) {
if (subEmbMmds[j].getPersistenceModifier() == FieldPersistenceModifier.PERSISTENT) {
addMappingForMember(subEmbCmd, subEmbMmds[j], embFmds);
}
}
}
}
}
}
use of org.datanucleus.metadata.InheritanceMetaData in project tests by datanucleus.
the class AnnotationTest method testBasic.
/**
* Test of basic JPA annotations reading capability
*/
public void testBasic() {
NucleusContext nucleusCtx = new PersistenceNucleusContextImpl("JPA", null);
MetaDataManager metaDataMgr = new JPAMetaDataManager(nucleusCtx);
ClassLoaderResolver clr = new ClassLoaderResolverImpl();
// Checks for Department
ClassMetaData cmd1 = (ClassMetaData) metaDataMgr.getMetaDataForClass(Department.class.getName(), clr);
String prefix = cmd1.getFullClassName() + " : ";
assertEquals(prefix + "detachable is wrong", cmd1.isDetachable(), true);
assertEquals(prefix + "identity-type is wrong", cmd1.getIdentityType(), IdentityType.APPLICATION);
assertEquals(prefix + "embedded-only is wrong", cmd1.isEmbeddedOnly(), false);
assertEquals(prefix + "requires-extent is wrong", cmd1.isRequiresExtent(), true);
assertEquals(prefix + "catalog is wrong", cmd1.getCatalog(), null);
assertEquals(prefix + "schema is wrong", cmd1.getSchema(), null);
assertEquals(prefix + "table is wrong", cmd1.getTable(), "JPA_AN_DEPARTMENT");
assertEquals(prefix + "has incorrect number of persistent fields", cmd1.getNoOfManagedMembers(), 4);
InheritanceMetaData inhmd1 = cmd1.getInheritanceMetaData();
assertEquals("Inheritance strategy is incorrect", InheritanceStrategy.NEW_TABLE, inhmd1.getStrategy());
// "projects"
AbstractMemberMetaData fmd = cmd1.getMetaDataForMember("projects");
assertNotNull(prefix + "doesnt have required field", fmd);
assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT);
assertFalse(prefix + "pk is wrong", fmd.isPrimaryKey());
assertFalse(prefix + "dfg is wrong", fmd.isDefaultFetchGroup());
assertTrue(prefix + "has no container specified!", fmd.getCollection() != null);
assertEquals(prefix + "should have collection of Project elements but hasnt", fmd.getCollection().getElementType(), Project.class.getName());
assertEquals(prefix + "shouldnt have collection of serialised elements but has", fmd.getCollection().isSerializedElement(), false);
assertEquals(prefix + "shouldnt have collection of dependent elements but has", fmd.getCollection().isDependentElement(), false);
// Checks for Project
ClassMetaData cmd2 = (ClassMetaData) metaDataMgr.getMetaDataForClass(Project.class.getName(), clr);
prefix = cmd2.getFullClassName() + " : ";
assertEquals(prefix + "detachable is wrong", true, cmd2.isDetachable());
assertEquals(prefix + "identity-type is wrong", cmd2.getIdentityType(), IdentityType.APPLICATION);
assertEquals(prefix + "objectid-class is wrong", "org.datanucleus.identity.StringId", cmd2.getObjectidClass());
assertEquals(prefix + "embedded-only is wrong", cmd2.isEmbeddedOnly(), false);
assertEquals(prefix + "requires-extent is wrong", cmd2.isRequiresExtent(), true);
assertEquals(prefix + "catalog is wrong", cmd2.getCatalog(), null);
assertEquals(prefix + "schema is wrong", cmd2.getSchema(), null);
assertEquals(prefix + "table is wrong", "JPA_AN_PROJECT", cmd2.getTable());
assertEquals(prefix + "has incorrect number of persistent fields", cmd2.getNoOfManagedMembers(), 2);
InheritanceMetaData inhmd2 = cmd2.getInheritanceMetaData();
assertEquals("Inheritance strategy is incorrect", InheritanceStrategy.NEW_TABLE, inhmd2.getStrategy());
// "name"
fmd = cmd2.getMetaDataForMember("name");
assertNotNull(prefix + "doesnt have required field", fmd);
assertTrue(prefix + "pk is wrong", fmd.isPrimaryKey());
assertTrue(prefix + "dfg is wrong", fmd.isDefaultFetchGroup());
assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT);
// "budget"
fmd = cmd2.getMetaDataForMember("budget");
assertNotNull(prefix + "doesnt have required field", fmd);
assertEquals(prefix + "has incorrect persistent field", fmd.getName(), "budget");
assertFalse(prefix + "pk is wrong", fmd.isPrimaryKey());
assertTrue(prefix + "dfg is wrong", fmd.isDefaultFetchGroup());
assertEquals(prefix + "should be persistent", fmd.getPersistenceModifier(), FieldPersistenceModifier.PERSISTENT);
}
use of org.datanucleus.metadata.InheritanceMetaData in project datanucleus-api-jdo by datanucleus.
the class JDOAnnotationReader method processClassAnnotations.
/**
* Method to process the "class" level annotations and create the outline ClassMetaData object.
* Supports classes annotated with @PersistenceCapable, classes annotated with @PersistenceAware, and classes which have neither of those but have @Queries or @Query.
* @param pmd Parent PackageMetaData
* @param cls The class
* @param annotations Annotations for this class
* @param clr ClassLoader resolver
* @return The ClassMetaData/InterfaceMetaData (or null if no annotations)
*/
protected AbstractClassMetaData processClassAnnotations(PackageMetaData pmd, Class cls, AnnotationObject[] annotations, ClassLoaderResolver clr) {
if (annotations == null || annotations.length == 0) {
return null;
}
AbstractClassMetaData cmd = null;
AnnotationObject pcAnnotation = isClassPersistable(annotations);
if (pcAnnotation != null) {
// PersistenceCapable class
cmd = (cls.isInterface()) ? pmd.newInterfaceMetadata(ClassUtils.getClassNameForClass(cls)) : pmd.newClassMetadata(ClassUtils.getClassNameForClass(cls));
cmd.setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_CAPABLE);
// Process all attributes here in case needed for other annotations
processPersistenceCapableAnnotation(cls, cmd, pcAnnotation.getNameValueMap());
} else if (isClassPersistenceAware(annotations)) {
// PersistenceAware class
cmd = pmd.newClassMetadata(ClassUtils.getClassNameForClass(cls));
cmd.setPersistenceModifier(ClassPersistenceModifier.PERSISTENCE_AWARE);
} else if (doesClassHaveNamedQueries(annotations)) {
// Class with named query specified
cmd = pmd.newClassMetadata(ClassUtils.getClassNameForClass(cls));
cmd.setPersistenceModifier(ClassPersistenceModifier.NON_PERSISTENT);
} else {
// Not involved in the persistence process
return null;
}
// Cater for named queries being specified on a persistence aware, or other class
processNamedQueries(cmd, cls, annotations);
if (cmd.getPersistenceModifier() != ClassPersistenceModifier.PERSISTENCE_CAPABLE) {
// Not persistable, so no further information needed
return cmd;
}
// Class is persistable so process annotations
for (AnnotationObject annotation : annotations) {
String annName = annotation.getName();
if (annName.equals(JDOAnnotationUtils.PERSISTENCE_CAPABLE)) {
// @PersistenceCapable is merged and processed above
continue;
}
Map<String, Object> annotationValues = annotation.getNameValueMap();
if (annName.equals(JDOAnnotationUtils.EMBEDDED_ONLY)) {
cmd.setEmbeddedOnly(true);
} else if (annName.equals(JDOAnnotationUtils.VERSION)) {
VersionStrategy versionStrategy = (VersionStrategy) annotationValues.get("strategy");
String strategy = JDOAnnotationUtils.getVersionStrategyString(versionStrategy);
String indexed = (String) annotationValues.get("indexed");
String column = (String) annotationValues.get("column");
Column[] columns = (Column[]) annotationValues.get("columns");
VersionMetaData vermd = new VersionMetaData();
vermd.setStrategy(strategy);
vermd.setColumnName(column);
vermd.setIndexed(IndexedValue.getIndexedValue(indexed));
if (columns != null && columns.length > 0) {
// Only use the first column
ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(columns[0]);
vermd.setColumnMetaData(colmd);
}
JDOAnnotationUtils.addExtensionsToMetaData(vermd, (Extension[]) annotationValues.get("extensions"));
vermd.setParent(cmd);
cmd.setVersionMetaData(vermd);
} else if (annName.equals(JDOAnnotationUtils.DATASTORE_IDENTITY)) {
String strategy = JDOAnnotationUtils.getValueGenerationStrategyString((IdGeneratorStrategy) annotationValues.get("strategy"));
String customStrategy = (String) annotationValues.get("customStrategy");
if (!StringUtils.isWhitespace(customStrategy)) {
// User has provided an extension strategy
strategy = customStrategy;
}
String sequence = (String) annotationValues.get("sequence");
String column = (String) annotationValues.get("column");
Column[] columns = (Column[]) annotationValues.get("columns");
IdentityMetaData idmd = new IdentityMetaData();
idmd.setColumnName(column);
idmd.setValueStrategy(ValueGenerationStrategy.getIdentityStrategy(strategy));
idmd.setSequence(sequence);
if (columns != null && columns.length > 0) {
// Only use the first column
ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(columns[0]);
idmd.setColumnMetaData(colmd);
}
JDOAnnotationUtils.addExtensionsToMetaData(idmd, (Extension[]) annotationValues.get("extensions"));
idmd.setParent(cmd);
cmd.setIdentityMetaData(idmd);
} else if (annName.equals(JDOAnnotationUtils.PRIMARY_KEY)) {
String pkName = (String) annotationValues.get("name");
String pkColumn = (String) annotationValues.get("column");
Column[] columns = (Column[]) annotationValues.get("columns");
PrimaryKeyMetaData pkmd = new PrimaryKeyMetaData();
pkmd.setName(pkName);
pkmd.setColumnName(pkColumn);
if (columns != null && columns.length > 0) {
for (Column column : columns) {
pkmd.addColumn(JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(column));
}
}
JDOAnnotationUtils.addExtensionsToMetaData(pkmd, (Extension[]) annotationValues.get("extensions"));
pkmd.setParent(cmd);
cmd.setPrimaryKeyMetaData(pkmd);
} else if (annName.equals(JDOAnnotationUtils.JOINS)) {
Join[] js = (Join[]) annotationValues.get("value");
if (js != null && js.length > 0) {
for (Join join : js) {
JoinMetaData joinmd = cmd.newJoinMetaData();
joinmd.setTable(join.table());
joinmd.setColumnName(join.column());
joinmd.setIndexed(IndexedValue.getIndexedValue(join.indexed()));
joinmd.setOuter(MetaDataUtils.getBooleanForString(join.outer(), false));
joinmd.setUnique(join.unique());
joinmd.setDeleteAction(JDOAnnotationUtils.getForeignKeyActionString(join.deleteAction()));
JDOAnnotationUtils.addExtensionsToMetaData(joinmd, join.extensions());
}
}
} else if (annName.equals(JDOAnnotationUtils.JOIN)) {
JoinMetaData joinmd = cmd.newJoinMetaData();
joinmd.setTable((String) annotationValues.get("table"));
joinmd.setColumnName((String) annotationValues.get("column"));
joinmd.setIndexed(IndexedValue.getIndexedValue((String) annotationValues.get("indexed")));
joinmd.setOuter(MetaDataUtils.getBooleanForString((String) annotationValues.get("outer"), false));
joinmd.setUnique((String) annotationValues.get("unique"));
joinmd.setDeleteAction(((ForeignKeyAction) annotationValues.get("deleteAction")).toString());
JDOAnnotationUtils.addExtensionsToMetaData(joinmd, (Extension[]) annotationValues.get("extensions"));
} else if (annName.equals(JDOAnnotationUtils.INHERITANCE)) {
String strategy = JDOAnnotationUtils.getInheritanceStrategyString((InheritanceStrategy) annotationValues.get("strategy"));
String customStrategy = (String) annotationValues.get("customStrategy");
if (!StringUtils.isWhitespace(customStrategy)) {
// User has provided an extension strategy
strategy = customStrategy;
}
InheritanceMetaData inhmd = cmd.getInheritanceMetaData();
if (inhmd == null) {
inhmd = cmd.newInheritanceMetadata();
}
inhmd.setStrategy(strategy);
} else if (annName.equals(JDOAnnotationUtils.DISCRIMINATOR)) {
DiscriminatorStrategy discriminatorStrategy = (DiscriminatorStrategy) annotationValues.get("strategy");
String strategy = JDOAnnotationUtils.getDiscriminatorStrategyString(discriminatorStrategy);
String column = (String) annotationValues.get("column");
String indexed = (String) annotationValues.get("indexed");
String value = (String) annotationValues.get("value");
Column[] columns = (Column[]) annotationValues.get("columns");
InheritanceMetaData inhmd = cmd.getInheritanceMetaData();
if (inhmd == null) {
inhmd = cmd.newInheritanceMetadata();
}
DiscriminatorMetaData dismd = inhmd.newDiscriminatorMetadata();
dismd.setColumnName(column);
dismd.setValue(value);
dismd.setStrategy(strategy);
dismd.setIndexed(indexed);
if (columns != null && columns.length > 0) {
// Only use the first column
ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(columns[0]);
dismd.setColumnMetaData(colmd);
}
} else if (annName.equals(JDOAnnotationUtils.FETCHPLANS)) {
FileMetaData filemd = (FileMetaData) pmd.getParent();
FetchPlan[] plans = (FetchPlan[]) annotationValues.get("value");
for (FetchPlan plan : plans) {
FetchPlanMetaData fpmd = filemd.newFetchPlanMetadata(plan.name());
fpmd.setFetchSize(plan.fetchSize());
fpmd.setMaxFetchDepth(plan.maxFetchDepth());
int numGroups = plan.fetchGroups().length;
for (int k = 0; k < numGroups; k++) {
fpmd.addFetchGroup(new FetchGroupMetaData(plan.fetchGroups()[k]));
}
}
} else if (annName.equals(JDOAnnotationUtils.FETCHPLAN)) {
FileMetaData filemd = (FileMetaData) pmd.getParent();
FetchPlanMetaData fpmd = filemd.newFetchPlanMetadata((String) annotationValues.get("name"));
fpmd.setFetchSize(((Integer) annotationValues.get("fetchSize")).intValue());
fpmd.setMaxFetchDepth(((Integer) annotationValues.get("maxFetchDepth")).intValue());
String[] fpFetchGroups = (String[]) annotationValues.get("fetchGroups");
for (String fpFetchGroup : fpFetchGroups) {
fpmd.addFetchGroup(new FetchGroupMetaData(fpFetchGroup));
}
} else if (annName.equals(JDOAnnotationUtils.FETCHGROUPS)) {
FetchGroup[] groups = (FetchGroup[]) annotationValues.get("value");
for (FetchGroup group : groups) {
FetchGroupMetaData fgmd = cmd.newFetchGroupMetaData(group.name());
if (!StringUtils.isWhitespace(group.postLoad())) {
fgmd.setPostLoad(Boolean.valueOf(group.postLoad()));
}
int numFields = group.members().length;
for (int k = 0; k < numFields; k++) {
FetchGroupMemberMetaData fgmmd = new FetchGroupMemberMetaData(fgmd, group.members()[k].name());
fgmmd.setRecursionDepth(group.members()[k].recursionDepth());
fgmd.addMember(fgmmd);
}
int numGroups = group.fetchGroups().length;
for (int k = 0; k < numGroups; k++) {
fgmd.addFetchGroup(new FetchGroupMetaData(group.fetchGroups()[k]));
}
}
} else if (annName.equals(JDOAnnotationUtils.FETCHGROUP)) {
FetchGroupMetaData fgmd = cmd.newFetchGroupMetaData((String) annotationValues.get("name"));
String postLoadStr = (String) annotationValues.get("postLoad");
if (!StringUtils.isWhitespace(postLoadStr)) {
fgmd.setPostLoad(Boolean.valueOf(postLoadStr));
}
Persistent[] fields = (Persistent[]) annotationValues.get("members");
if (fields != null) {
for (Persistent field : fields) {
FetchGroupMemberMetaData fgmmd = new FetchGroupMemberMetaData(fgmd, field.name());
fgmmd.setRecursionDepth(field.recursionDepth());
fgmd.addMember(fgmmd);
}
}
} else if (annName.equals(JDOAnnotationUtils.SEQUENCE)) {
String seqName = (String) annotationValues.get("name");
String seqStrategy = JDOAnnotationUtils.getSequenceStrategyString((SequenceStrategy) annotationValues.get("strategy"));
String seqSeq = (String) annotationValues.get("datastoreSequence");
Class seqFactory = (Class) annotationValues.get("factoryClass");
String seqFactoryClassName = null;
if (seqFactory != null && seqFactory != void.class) {
seqFactoryClassName = seqFactory.getName();
}
Integer seqSize = (Integer) annotationValues.get("allocationSize");
Integer seqStart = (Integer) annotationValues.get("initialValue");
if (StringUtils.isWhitespace(seqName)) {
throw new InvalidClassMetaDataException("044155", cmd.getFullClassName());
}
SequenceMetaData seqmd = new SequenceMetaData(seqName, seqStrategy);
seqmd.setFactoryClass(seqFactoryClassName);
seqmd.setDatastoreSequence(seqSeq);
if (seqSize != null) {
seqmd.setAllocationSize(seqSize);
}
if (seqStart != null) {
seqmd.setInitialValue(seqStart);
}
JDOAnnotationUtils.addExtensionsToMetaData(seqmd, (Extension[]) annotationValues.get("extensions"));
// Sequence - currently only allowing 1 per class (should really be on the package)
cmd.getPackageMetaData().addSequence(seqmd);
} else if (annName.equals(JDOAnnotationUtils.INDICES)) {
// Multiple Indices for the class
Index[] values = (Index[]) annotationValues.get("value");
if (values != null && values.length > 0) {
for (Index idx : values) {
IndexMetaData idxmd = JDOAnnotationUtils.getIndexMetaData(idx.name(), idx.table(), "" + idx.unique(), idx.members(), idx.columns());
if (idxmd.getNumberOfColumns() == 0 && idxmd.getNumberOfMembers() == 0) {
NucleusLogger.METADATA.warn(Localiser.msg("044204", cls.getName()));
} else {
cmd.addIndex(idxmd);
idxmd.setParent(cmd);
}
}
}
} else if (annName.equals(JDOAnnotationUtils.INDEX)) {
// Single Index for the class
String name = (String) annotationValues.get("name");
String table = (String) annotationValues.get("table");
String unique = (String) annotationValues.get("unique");
String[] members = (String[]) annotationValues.get("members");
Column[] columns = (Column[]) annotationValues.get("columns");
IndexMetaData idxmd = JDOAnnotationUtils.getIndexMetaData(name, table, unique, members, columns);
JDOAnnotationUtils.addExtensionsToMetaData(idxmd, (Extension[]) annotationValues.get("extensions"));
if (idxmd.getNumberOfColumns() == 0 && idxmd.getNumberOfMembers() == 0) {
NucleusLogger.METADATA.warn(Localiser.msg("044204", cls.getName()));
} else {
cmd.addIndex(idxmd);
idxmd.setParent(cmd);
}
} else if (annName.equals(JDOAnnotationUtils.UNIQUES)) {
// Multiple Unique Constraints for the class
Unique[] values = (Unique[]) annotationValues.get("value");
if (values != null && values.length > 0) {
for (Unique uni : values) {
UniqueMetaData unimd = JDOAnnotationUtils.getUniqueMetaData(uni.name(), uni.table(), "" + uni.deferred(), uni.members(), uni.columns());
if (unimd.getNumberOfColumns() == 0 && unimd.getNumberOfMembers() == 0) {
NucleusLogger.METADATA.warn(Localiser.msg("044205", cls.getName()));
} else {
cmd.addUniqueConstraint(unimd);
unimd.setParent(cmd);
}
}
}
} else if (annName.equals(JDOAnnotationUtils.UNIQUE)) {
// Single Unique constraint for the class
String name = (String) annotationValues.get("name");
String table = (String) annotationValues.get("table");
String deferred = (String) annotationValues.get("deferred");
String[] members = (String[]) annotationValues.get("members");
Column[] columns = (Column[]) annotationValues.get("columns");
UniqueMetaData unimd = JDOAnnotationUtils.getUniqueMetaData(name, table, deferred, members, columns);
JDOAnnotationUtils.addExtensionsToMetaData(unimd, (Extension[]) annotationValues.get("extensions"));
if (unimd.getNumberOfColumns() == 0 && unimd.getNumberOfMembers() == 0) {
NucleusLogger.METADATA.warn(Localiser.msg("044205", cls.getName()));
} else {
cmd.addUniqueConstraint(unimd);
unimd.setParent(cmd);
}
} else if (annName.equals(JDOAnnotationUtils.FOREIGNKEYS)) {
// Multiple FKs for the class
ForeignKey[] values = (ForeignKey[]) annotationValues.get("value");
if (values != null && values.length > 0) {
for (ForeignKey fk : values) {
String deleteAction = JDOAnnotationUtils.getForeignKeyActionString(fk.deleteAction());
String updateAction = JDOAnnotationUtils.getForeignKeyActionString(fk.updateAction());
ForeignKeyMetaData fkmd = JDOAnnotationUtils.getFKMetaData(fk.name(), fk.table(), fk.unique(), "" + fk.deferred(), deleteAction, updateAction, fk.members(), fk.columns());
if (fkmd.getNumberOfColumns() == 0 && fkmd.getNumberOfMembers() == 0) {
NucleusLogger.METADATA.warn(Localiser.msg("044206", cls.getName()));
} else {
cmd.addForeignKey(fkmd);
fkmd.setParent(cmd);
}
}
}
} else if (annName.equals(JDOAnnotationUtils.FOREIGNKEY)) {
// Single FK constraint for the class
String name = (String) annotationValues.get("name");
String table = (String) annotationValues.get("table");
String unique = (String) annotationValues.get("unique");
String deferred = (String) annotationValues.get("deferred");
String deleteAction = JDOAnnotationUtils.getForeignKeyActionString((ForeignKeyAction) annotationValues.get("deleteAction"));
String updateAction = JDOAnnotationUtils.getForeignKeyActionString((ForeignKeyAction) annotationValues.get("updateAction"));
String[] members = (String[]) annotationValues.get("members");
Column[] columns = (Column[]) annotationValues.get("columns");
ForeignKeyMetaData fkmd = JDOAnnotationUtils.getFKMetaData(name, table, unique, deferred, deleteAction, updateAction, members, columns);
JDOAnnotationUtils.addExtensionsToMetaData(fkmd, (Extension[]) annotationValues.get("extensions"));
if (fkmd.getNumberOfColumns() == 0 && fkmd.getNumberOfMembers() == 0) {
NucleusLogger.METADATA.warn(Localiser.msg("044206", cls.getName()));
} else {
cmd.addForeignKey(fkmd);
fkmd.setParent(cmd);
}
} else if (annName.equals(JDOAnnotationUtils.COLUMNS)) {
// Unmapped column specification
Column[] cols = (Column[]) annotationValues.get("value");
if (cols != null && cols.length > 0) {
for (Column col : cols) {
ColumnMetaData colmd = JDOAnnotationUtils.getColumnMetaDataForColumnAnnotation(col);
JDOAnnotationUtils.addExtensionsToMetaData(colmd, col.extensions());
colmd.setParent(cmd);
cmd.addUnmappedColumn(colmd);
}
}
} else if (annName.equals(JDOAnnotationUtils.CACHEABLE)) {
String cache = (String) annotationValues.get("value");
if (cache != null && cache.equalsIgnoreCase("false")) {
cmd.setCacheable(false);
}
} else if (annName.equals(JDOAnnotationUtils.EXTENSIONS)) {
Extension[] values = (Extension[]) annotationValues.get("value");
if (values != null && values.length > 0) {
for (Extension ext : values) {
String vendorName = ext.vendorName();
if (StringUtils.isWhitespace(vendorName)) {
throw new InvalidMetaDataException("044160", vendorName, ext.key().toString(), ext.value().toString());
} else if (vendorName.equalsIgnoreCase(MetaData.VENDOR_NAME)) {
cmd.addExtension(ext.key().toString(), ext.value().toString());
}
}
}
} else if (annName.equals(JDOAnnotationUtils.EXTENSION)) {
String vendorName = (String) annotationValues.get("vendorName");
if (StringUtils.isWhitespace(vendorName)) {
throw new InvalidMetaDataException("044160", vendorName, annotationValues.get("key"), annotationValues.get("value"));
} else if (vendorName.equalsIgnoreCase(MetaData.VENDOR_NAME)) {
cmd.addExtension((String) annotationValues.get("key"), (String) annotationValues.get("value"));
}
} else {
if (!annName.equals(JDOAnnotationUtils.PERSISTENCE_AWARE) && !annName.equals(JDOAnnotationUtils.QUERIES) && !annName.equals(JDOAnnotationUtils.QUERY)) {
NucleusLogger.METADATA.debug(Localiser.msg("044203", cls.getName(), annotation.getName()));
}
}
}
NucleusLogger.METADATA.debug(Localiser.msg("044200", cls.getName(), "JDO"));
return cmd;
}
use of org.datanucleus.metadata.InheritanceMetaData in project datanucleus-api-jdo by datanucleus.
the class TypeMetadataImpl method newInheritanceMetadata.
public InheritanceMetadata newInheritanceMetadata() {
InheritanceMetaData internalInhmd = getInternal().newInheritanceMetadata();
InheritanceMetadataImpl inhmd = new InheritanceMetadataImpl(internalInhmd);
inhmd.parent = this;
return inhmd;
}
use of org.datanucleus.metadata.InheritanceMetaData in project datanucleus-rdbms by datanucleus.
the class RDBMSStoreHelper method getClassNameForIdUsingUnion.
/**
* Utility that does a union candidate query for the specified candidate(s) and subclasses
* and returns the class name of the instance that has the specified identity (if any).
* @param storeMgr RDBMS StoreManager
* @param ec execution context
* @param id The id
* @param rootCmds Metadata for the classes at the root
* @return Name of the class with this identity (or null if none found)
*/
public static String getClassNameForIdUsingUnion(RDBMSStoreManager storeMgr, ExecutionContext ec, Object id, List<AbstractClassMetaData> rootCmds) {
// Check for input error
if (rootCmds == null || rootCmds.isEmpty() || id == null) {
return null;
}
SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
ClassLoaderResolver clr = ec.getClassLoaderResolver();
// Form a query UNIONing all possible root candidates (and their subclasses)
Iterator<AbstractClassMetaData> rootCmdIter = rootCmds.iterator();
// Metadata for sample class in the tree so we can check if needs locking
AbstractClassMetaData sampleCmd = null;
SelectStatement sqlStmtMain = null;
while (rootCmdIter.hasNext()) {
AbstractClassMetaData rootCmd = rootCmdIter.next();
DatastoreClass rootTbl = storeMgr.getDatastoreClass(rootCmd.getFullClassName(), clr);
InheritanceMetaData rootInhmd = rootCmd.getBaseAbstractClassMetaData().getInheritanceMetaData();
if (rootInhmd.getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
// COMPLETE TABLE so use one branch of UNION for each possible class
if (rootTbl != null) {
UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, clr.classForName(rootCmd.getFullClassName()), false, null, null);
stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
if (sqlStmtMain == null) {
sampleCmd = rootCmd;
sqlStmtMain = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmtMain.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmtMain, sqlStmtMain.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmtMain, idParamMapping, id, "ID");
sqlStmtMain.whereAnd(fieldExpr.eq(fieldVal), true);
} else {
SelectStatement sqlStmt = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmt, idParamMapping, id, "ID");
sqlStmt.whereAnd(fieldExpr.eq(fieldVal), true);
sqlStmtMain.union(sqlStmt);
}
}
Collection<String> rootSubclassNames = storeMgr.getSubClassesForClass(rootCmd.getFullClassName(), true, clr);
for (String rootSubclassName : rootSubclassNames) {
AbstractClassMetaData rootSubclassCmd = storeMgr.getMetaDataManager().getMetaDataForClass(rootSubclassName, clr);
DatastoreClass rootSubclassTbl = storeMgr.getDatastoreClass(rootSubclassCmd.getFullClassName(), clr);
if (rootSubclassTbl != null) {
UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, clr.classForName(rootSubclassCmd.getFullClassName()), false, null, null);
stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
if (sqlStmtMain == null) {
sampleCmd = rootSubclassCmd;
sqlStmtMain = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmtMain.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmtMain, sqlStmtMain.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmtMain, idParamMapping, id, "ID");
sqlStmtMain.whereAnd(fieldExpr.eq(fieldVal), true);
} else {
SelectStatement sqlStmt = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmt, idParamMapping, id, "ID");
sqlStmt.whereAnd(fieldExpr.eq(fieldVal), true);
sqlStmtMain.union(sqlStmt);
}
}
}
continue;
}
if (rootTbl == null) {
// Class must be using "subclass-table" (no table of its own) so find where it is
AbstractClassMetaData[] subcmds = storeMgr.getClassesManagingTableForClass(rootCmd, clr);
if (subcmds == null || subcmds.length == 0) {
// No table for this class so ignore
} else {
for (int i = 0; i < subcmds.length; i++) {
UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, clr.classForName(subcmds[i].getFullClassName()), true, null, null);
stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
if (sqlStmtMain == null) {
sampleCmd = subcmds[i];
sqlStmtMain = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmtMain.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmtMain, sqlStmtMain.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmtMain, idParamMapping, id, "ID");
sqlStmtMain.whereAnd(fieldExpr.eq(fieldVal), true);
} else {
SelectStatement sqlStmt = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmt, idParamMapping, id, "ID");
sqlStmt.whereAnd(fieldExpr.eq(fieldVal), true);
sqlStmtMain.union(sqlStmt);
}
}
}
} else {
UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, clr.classForName(rootCmd.getFullClassName()), true, null, null);
stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
if (sqlStmtMain == null) {
sampleCmd = rootCmd;
sqlStmtMain = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmtMain.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmtMain, sqlStmtMain.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmtMain, idParamMapping, id, "ID");
sqlStmtMain.whereAnd(fieldExpr.eq(fieldVal), true);
} else {
SelectStatement sqlStmt = stmtGen.getStatement(ec);
// WHERE (object id) = ?
JavaTypeMapping idMapping = sqlStmt.getPrimaryTable().getTable().getIdMapping();
JavaTypeMapping idParamMapping = new PersistableIdMapping((PersistableMapping) idMapping);
SQLExpression fieldExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), idMapping);
SQLExpression fieldVal = exprFactory.newLiteralParameter(sqlStmt, idParamMapping, id, "ID");
sqlStmt.whereAnd(fieldExpr.eq(fieldVal), true);
sqlStmtMain.union(sqlStmt);
}
}
}
// Perform the query
if (sqlStmtMain != null) {
try {
ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
SQLController sqlControl = storeMgr.getSQLController();
if (sampleCmd != null && ec.getSerializeReadForClass(sampleCmd.getFullClassName())) {
sqlStmtMain.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
}
try {
PreparedStatement ps = SQLStatementHelper.getPreparedStatementForSQLStatement(sqlStmtMain, ec, mconn, null, null);
String statement = sqlStmtMain.getSQLText().toSQL();
try {
ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, statement, ps);
try {
while (rs.next()) {
try {
return rs.getString(UnionStatementGenerator.DN_TYPE_COLUMN).trim();
} catch (SQLException sqle) {
}
}
} finally {
rs.close();
}
} finally {
sqlControl.closeStatement(mconn, ps);
}
} finally {
mconn.release();
}
} catch (SQLException sqe) {
NucleusLogger.DATASTORE.error("Exception with UNION statement", sqe);
throw new NucleusDataStoreException(sqe.toString());
}
}
return null;
}
Aggregations