Passing an association to a Java Action

2
I need to process 2 related 'any objects' in java. How can I pass the association between the 'Any objects' or can I find it by code?
asked
3 answers
4

Given that there is only one association between the two objects you can retrieve a list of associations from both and find the intersect of the collection. Something like

Collection<? extends IMetaAssociation> metaAssociationsP1 = metaObject1.getDeclaredMetaAssociationsParent();
Collection<? extends IMetaAssociation> metaAssociationsC1 = metaObject1.getDeclaredMetaAssociationsChild();

Collection<? extends IMetaAssociation> metaAssociationsP2 = metaObject2.getDeclaredMetaAssociationsParent();
Collection<? extends IMetaAssociation> metaAssociationsC2 = metaObject2.getDeclaredMetaAssociationsChild();

metaAssociationsP1.retainAll(metaAssociationsC2);
metaAssociationsC1.retainAll(metaAssociationsP2);

if (metaAssociationsP1.size()==1)
  association=metaAssociationsP1.get(0);
...

BTW: I have not tested this code!

answered
2

Let's assume you have a Customer object and an Order object which are related.

You can just pass one of the object to the java action (e.g. Customer). If the association is set you can use the Customer.getOrder() function to retrieve the order. The Mendix runtime will make sure you get the right Order object.

This only works if you know what entities you put into the Java action. If you really have two "any objects" without knowing their associations you need to search the model definition for associations like Bart states in his answer.

answered
1

Thanks Bart,

I finished the code. The for statements are not elegant but work.

    public String getAssociationBetweenEntities(IMendixObject CurrentEntity, IMendixObject AssociatedEntity) throws Exception
{
    String association = "";
    Collection<? extends IMetaAssociation> metaAssociationsP1 = CurrentEntity.getMetaObject().getDeclaredMetaAssociationsParent();
    Collection<? extends IMetaAssociation> metaAssociationsC1 = CurrentEntity.getMetaObject().getDeclaredMetaAssociationsChild();

    Collection<? extends IMetaAssociation> metaAssociationsP2 = AssociatedEntity.getMetaObject().getDeclaredMetaAssociationsParent();
    Collection<? extends IMetaAssociation> metaAssociationsC2 = AssociatedEntity.getMetaObject().getDeclaredMetaAssociationsChild();


    // remove all unequal associations
    metaAssociationsP1.retainAll(metaAssociationsC2);
    metaAssociationsC1.retainAll(metaAssociationsP2);

    // should be one record
    for( IMetaAssociation curMetaAssociation : metaAssociationsC1 ) {
        association = curMetaAssociation.getName();
    }
    // not found? try the other way around
    if (association.isEmpty()) {
        for( IMetaAssociation curMetaAssociation : metaAssociationsP1 ) {
            association = curMetaAssociation.getName();
        }
    }

    return association;
}
// END EXTRA CODE
answered