Mendix entities are the foundation of any Mendix solution. Sometimes however, like the nautilus, you might need to submerge into some Java code in order to create Mendix entitles. The 3 lines of Java code below give an example of how that can be achieved.
The IMendixObject is the Mendix platform’s abstract entity class that all entities are created from. The class has a feast of helpful methods but for this short tutorial we’re just going to deal with how to create and set a value against the entity.
// BEGIN USER CODE
IMendixObject myEntity = Core.instantiate(getContext(), TestEntity.entityName.toString());
myEntity.setValue(getContext(), TestEntity.MemberNames.name.toString(), “John Smith");
// END USER CODE
Core.instantiate returns a static IMendixObject object from which you can attach attribute information to. As you can see the second parameter of the instantiate method takes in a String parameter of the type of object it must create.You can do this by inserting a simple string but a stricter way to would be to reference the actual entity class. In the example I created an entity called “TestEntity” and used the toString method on the entityName attribute to get string value of the object type for that entity. I can use the toString method because when you create an Entity via the moddler Mendix actually creates a class called “TestEntity” and sets a final static string with the value of the entity name against it.
Pro Tip: It’s better to create your entity’s using the above “toString” method because it allows some measure of security when refactoring entity names. For example, if I were to change the entity name from “TestEntity” to “Order” then this Java code will fail at compile time. If you create the IMendixObject via using a string “MyFirstModule.TestEntity” then it will fail at runtime when the instantiate method can’t find an entity with that exact name.
The setValue method on the IMendixObject allows you to create an attribute against the entity. In this case I create the value “John Smith” against the “MemberName” attribute of the IMendixObject entity.
Remember how I said before that Mendix effectively creates a class per entity you create in the moddlers. Well, it also creates the entity attributes on the entity as enums. That’s cool for 2 reasons:
- Code complete IDE’s like eclipse will pick up the attribute names making it easier to code
- Similar to the point above, you can simply refactor the attribute names have any errors picked up at combine time.
The last course of action is to commit the object to persistence using the Core.commit function – that’s done via the commit method on the last line.
It’s great that Mendix offers the flexibility to create entities so simply under the surface through Java.