How to: Locking in Mendix to get a unique number
A few days after our flying start in Mendix, we ran into a nice Mendix challenge. We found out that Mendix doesn't have a default mechanism to lock entities. But sometimes you need it to get things done. In our case we'd like to have unique numbers. Unique for each order and unique for each organisation we have in the system. Autonumbering wiIl not work, because each organisation want to choose their own starting number. If you want to do this on the fly, you need a locking mechanism to avoid duplicate numbers.
In the past there was a app store module facilitating this, but Mendix removed the support for that. Because it doesn't work well when applications are horizontally scaled.
We looked for a way around and - together with Bart Luijten from Mendix - we found an interesting and easy to implement solution. It's based on the fact that a microflow waits to change an entity when this entity is changed and committed in another, parallel running microflow.
How it works: define an entity holding your number sequence and add a boolean field to store if the sequence is locked or not.
In this example we have a sequence number per organisation with a Long field for the numbering and a boolean field Locked to store the locking state.
Now it's time for the trick. Create a flow to get your ordernumber and define it as shown in the picture below.
When the first flow is finished (and technically the microflow transaction is committed) the second flow will continue, Be aware to retrieve the sequence again (second step), because the first microflow changed it and your first retrieved sequence isn't updated automatically.
In the third step you change your sequence number to the next one and reset the locked field. Then pass the sequence number into the order and ready!
Written by Kees de Kraker