EntityManager.persist & Transaction.commit not working for User and UserRole

Hi there, I am facing trouble executing the following transaction.

private void populateDatabase(Set<String> newUsers, UUID groupId, UUID roleId) {

        Transaction tx = persistence.createTransaction();
        try {
            EntityManager em = persistence.getEntityManager();
            for (String username : newUsers) {
                User user = metadata.create(User.class);
                user.setLogin(username);
                user.setActive(true);
                user.setLanguage("en");
                user.setChangePasswordAtNextLogon(false);
                user.setGroup(em.getReference(Group.class, groupId));
                em.persist(user);

                UserRole userRole = metadata.create(UserRole.class);
                userRole.setUser(user);
                userRole.setRole(em.getReference(Role.class, roleId));
                em.persist(userRole);
            }
            tx.commit();
        } finally {
            tx.end();
        }
    }

It seems that ‘em.persist(user)’ executes as expected but ‘tx.commit()’ throws an exception saying that user with that record is already inserted in database.

I tried to remove commit method and the user with userRole is persisted but version, createTs fields are not populated and later I am not able to delete these users. UI message there is “User has been modified in another transaction”.

Please, advice how to change the code to work appropriately.
I am using Cuba Studio 6.8.2.

Best regards!

Hi Dop,

I am not sure why you are using this way to persist, I think but not sure that the reason might be because of the Transaction tx has a separate life cycle than the entity manager, if i were you i would try a different way and most likely it will work, please try this:

@Transactional
private void populateDatabase(Set<String> newUsers, UUID groupId, UUID roleId) {
            EntityManager em = persistence.getEntityManager();
            for (String username : newUsers) {
                User user = metadata.create(User.class);
                user.setLogin(username);
                user.setActive(true);
                user.setLanguage("en");
                user.setChangePasswordAtNextLogon(false);
                //user.setPassword("password");
                user.setGroup(em.getReference(Group.class, groupId));
                em.persist(user);

                UserRole userRole = metadata.create(UserRole.class);
                userRole.setUser(user);
                userRole.setRole(em.getReference(Role.class, roleId));
                em.persist(userRole);
    }

note that the password has to be defined in the code as it’s mandatory.

Hi @dop1010

Your code looks correct. Make sure created users have distinct logins (case-insensitive).

Thank you @knstvk for your answer!

It seems like tx.commit() is cannot be executed because login_lc already exists. It exists because of em.persist(user) method.

Please have a look at the exception thrown when I am trying to record 2 new users:

12:06:00.284 INFO  c.m.a.s.UpdateUsersSchedulerTaskBean - User: user1.user1 ADDED!
12:06:00.301 INFO  c.m.a.s.UpdateUsersSchedulerTaskBean - ROLE: ConferenceEditor given to USER: user1.user1...
12:06:00.302 INFO  c.m.a.s.UpdateUsersSchedulerTaskBean - User: user2.user2 ADDED!
12:06:00.302 INFO  c.m.a.s.UpdateUsersSchedulerTaskBean - ROLE: ConferenceEditor given to USER: user2.user2...
12:06:00.391 ERROR c.h.c.core.app.scheduling.RunnerBean - Error running ScheduledTask{9d9264ce-885b-5b85-ec27-21c592bd35d7, beanName=admin_UpdateUsersScheduledService, methodName=udpateUsersFromAD, period=120}
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.haulmont.cuba.core.app.scheduling.RunnerBean.executeTask(RunnerBean.java:217) ~[cuba-core-6.8.5.jar:6.8.5]
        at com.haulmont.cuba.core.app.scheduling.RunnerBean.lambda$runTask$0(RunnerBean.java:124) ~[cuba-core-6.8.5.jar:6.8.5]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_161]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_161]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[na:1.8.0_161]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[na:1.8.0_161]
        at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_161]
Caused by: java.lang.reflect.InvocationTargetException: null
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
        at com.haulmont.cuba.core.app.scheduling.RunnerBean.executeTask(RunnerBean.java:215) ~[cuba-core-6.8.5.jar:6.8.5]
        ... 6 common frames omitted
Caused by: org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.cuba22): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "idx_sec_user_uniq_login"
  Detail: Key (login_lc)=(user2.user2) already exists.
Error Code: 0
Call: INSERT INTO SEC_USER (ID, ACTIVE, CHANGE_PASSWORD_AT_LOGON, CREATE_TS, CREATED_BY, DELETE_TS, DELETED_BY, EMAIL, FIRST_NAME, IP_MASK, LANGUAGE_, LAST_NAME, LOGIN, LOGIN_LC, MIDDLE_NAME, NAME, PASSWORD, POSITION_, TIME_ZONE, TIME_ZONE_AUTO, UPDATE_TS, UPDATED_BY, VERSION, GROUP_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        bind => [d5ba7613-98b0-2416-c101-a7f0c9a700f8, true, false, 2019-01-02 12:06:00.301, admin, null, null, null, null, null, en, null, user2.user2, user2.user2, null, null, null, null, null, null, 2019-01-02 12:06:00.301, null, 1, 1a525c0c-f356-983c-4bd0-2c2740f7dac0]
Query: InsertObjectQuery(com.haulmont.cuba.security.entity.User-d5ba7613-98b0-2416-c101-a7f0c9a700f8 [new,managed])
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:526) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at com.haulmont.cuba.core.sys.TransactionImpl.commit(TransactionImpl.java:104) ~[cuba-core-6.8.5.jar:6.8.5]
        at com.musala.admin.scheduled.UpdateUsersSchedulerTaskBean.udpateUsersFromAD(UpdateUsersSchedulerTaskBean.java:75) ~[admin-core-1.0.3-SNAPSHOT.jar:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at com.sun.proxy.$Proxy293.udpateUsersFromAD(Unknown Source) ~[na:na]
        ... 11 common frames omitted
Caused by: javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.cuba22): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "idx_sec_user_uniq_login"
  Detail: Key (login_lc)=(user2.user2) already exists.
Error Code: 0
Call: INSERT INTO SEC_USER (ID, ACTIVE, CHANGE_PASSWORD_AT_LOGON, CREATE_TS, CREATED_BY, DELETE_TS, DELETED_BY, EMAIL, FIRST_NAME, IP_MASK, LANGUAGE_, LAST_NAME, LOGIN, LOGIN_LC, MIDDLE_NAME, NAME, PASSWORD, POSITION_, TIME_ZONE, TIME_ZONE_AUTO, UPDATE_TS, UPDATED_BY, VERSION, GROUP_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        bind => [d5ba7613-98b0-2416-c101-a7f0c9a700f8, true, false, 2019-01-02 12:06:00.301, admin, null, null, null, null, null, en, null, user2.user2, user2.user2, null, null, null, null, null, null, 2019-01-02 12:06:00.301, null, 1, 1a525c0c-f356-983c-4bd0-2c2740f7dac0]
Query: InsertObjectQuery(com.haulmont.cuba.security.entity.User-d5ba7613-98b0-2416-c101-a7f0c9a700f8 [new,managed])
        at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:159) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517) ~[spring-orm-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 28 common frames omitted
Caused by: org.eclipse.persistence.exceptions.DatabaseException:
Internal Exception: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "idx_sec_user_uniq_login"
  Detail: Key (login_lc)=(user2.user2) already exists.
Error Code: 0
Call: INSERT INTO SEC_USER (ID, ACTIVE, CHANGE_PASSWORD_AT_LOGON, CREATE_TS, CREATED_BY, DELETE_TS, DELETED_BY, EMAIL, FIRST_NAME, IP_MASK, LANGUAGE_, LAST_NAME, LOGIN, LOGIN_LC, MIDDLE_NAME, NAME, PASSWORD, POSITION_, TIME_ZONE, TIME_ZONE_AUTO, UPDATE_TS, UPDATED_BY, VERSION, GROUP_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        bind => [d5ba7613-98b0-2416-c101-a7f0c9a700f8, true, false, 2019-01-02 12:06:00.301, admin, null, null, null, null, null, en, null, user2.user2, user2.user2, null, null, null, null, null, null, 2019-01-02 12:06:00.301, null, 1, 1a525c0c-f356-983c-4bd0-2c2740f7dac0]
Query: InsertObjectQuery(com.haulmont.cuba.security.entity.User-d5ba7613-98b0-2416-c101-a7f0c9a700f8 [new])
        at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.processExceptionForCommError(DatabaseAccessor.java:1651) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:931) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:995) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:636) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:544) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2052) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:306) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.executeCall(ExpressionQueryMechanism.java:2863) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:377) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:165) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:180) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:489) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:301) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:904) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:803) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2944) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1854) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1836) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1787) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:227) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsForClassWithChangeSet(CommitManager.java:194) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:139) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4260) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1446) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1536) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:278) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1174) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:134) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        ... 29 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "idx_sec_user_uniq_login"
  Detail: Key (login_lc)=(user2.user2) already exists.
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:288) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:168) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:135) ~[postgresql-9.4.1212.jar:9.4.1212]
        at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:97) ~[tomcat-dbcp.jar:8.5.23]
        at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:97) ~[tomcat-dbcp.jar:8.5.23]
        at com.haulmont.cuba.core.sys.jdbc.ProxyPreparedStatement.lambda$executeUpdate$1(ProxyPreparedStatement.java:39) ~[cuba-core-6.8.5.jar:6.8.5]
        at com.haulmont.cuba.core.sys.jdbc.ProxyStatement.executeSqlStatement(ProxyStatement.java:257) ~[cuba-core-6.8.5.jar:6.8.5]
        at com.haulmont.cuba.core.sys.jdbc.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:39) ~[cuba-core-6.8.5.jar:6.8.5]
        at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:923) ~[eclipselink-2.6.2.cuba22.jar:2.6.2.cuba22]
        ... 62 common frames omitted

So the exception clearly shows that you are trying to create a user with a login which already exists. Maybe you pass the same values to your method multiple times.

Thank you @knstvk!

I managed to fix it. The problem was not what you suggested as the input was with unique records.
There was an issue with “em.persist(user)” and “em.persist(userRole)” methods.
User and userRoles are related and the second persist cannot be executed.

Regards!

So how did you change the code? Just curious…

I am sending the working code.
@Transactional annotation did not resolve the problem, but removing “em.persist(userRole)” did.

@Transactional
private void populateDatabase(Set<String> newUsers, UUID groupId, UUID roleId) {
            EntityManager em = persistence.getEntityManager();
            for (String username : newADUsers) {
                User user = metadata.create(User.class);
                user.setLogin(username);
                user.setActive(true);
                user.setLanguage("en");
                user.setChangePasswordAtNextLogon(false);
                user.setGroup(em.getReference(Group.class, groupId));

                UserRole userRole = metadata.create(UserRole.class);
                userRole.setUser(user);
                userRole.setRole(em.getReference(Role.class, roleId));

                em.persist(user);
            }
}

Thank you for the support!

I still don’t understand why it works for you. The UserRole object is not stored in the database in the last case.

I am guessing the snippet might be missing em.persist(userRole) at the end.

Perhaps the reason for it is because UserRole I am setting is the default one.

A post was split to a new topic: How to make a localized message for this kind of exception?