Run some code before user creation


Is it possible to run some code before user creation? I would like to check how many users are in the system and prevent creating more users if let’s say the user count already reached 10.

Would this be possible?


Hi Zoltan,

Sure you can do it.

If you are on CUBA 6.10 or 7+, I would recommend using EntityChangedEvent.
First, define the event listener in a middle tier bean:


import com.haulmont.cuba.core.TransactionalDataManager;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.UUID;

public class UserChangeListener {
    public static final String NAME = "sales_UserChangeListener";

    private TransactionalDataManager txDataManager;

    private void onUserChanged(EntityChangedEvent<User, UUID> event) {
        if (event.getType() == EntityChangedEvent.Type.CREATED) {
            Long count = txDataManager.loadValue("select count(u) from sec$User u", Long.class).one();
            if (count > 3) {
                throw new RuntimeException("Exceeded maximum number of registered users");

Usage of TransactionalDataManager is crucial here - you must execute the query in the current transaction, otherwise the deadlock on the database level may occur.

Next, we need to make the framework to send EntityChangedEvent when a User is changed. Obviously, we cannot add @PublishEntityChangedEvents annotation on the entity class as it is out of our control. So we will make use of the metadata annotations feature and define the annotation for User in the metadata.xml file:

<metadata xmlns="">

    <metadata-model root-package="" namespace="sales"/>

        <entity class="">
            <annotation name="com.haulmont.cuba.core.entity.annotation.PublishEntityChangedEvents">
                <attribute name="created" value="true"/>
                <attribute name="updated" value="false"/>
                <attribute name="deleted" value="false"/>


That’s all - the code checking the number of users will be invoked on each user creation. If the exception is thrown, the transaction is rolled back and the user is not saved.

If you are on CUBA version prior to 6.10, use an entity listener for User as described in the documentation on dynamic registration of entity listeners. In this case, you need EntityManager to execute the query.