grails-core icon indicating copy to clipboard operation
grails-core copied to clipboard

Error flush transaction

Open Noirtam opened this issue 1 month ago • 2 comments

Expected Behavior

Since migration 6 (maybe 7.0.0-RC1) to 7.0.0, I have an error hibernate when I'm trying save two domains in the same transaction :

Utilisateur.withNewTransaction {
            //Creation utilisateur admin
            if (Utilisateur.countByUsername("test") == 0) {
                Role roleAdmin = Role.findByAuthority("ROLE_ADMIN")
                Utilisateur userAdmin = new Utilisateur(username: "test", password: "test", email: "[email protected]").save(flush: true, failOnError: true)
                new UtilisateurRole(utilisateur: userAdmin, role: roleAdmin).save(flush: true, failOnError: true)
            }
        }

Error :


org.springframework.orm.hibernate5.HibernateObjectRetrievalFailureException: No row with the given identifier exists: [org.monprojet.Utilisateur#13]
        at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:238)

Actual Behaviour

No response

Steps To Reproduce

  1. Try to create new relation between two domain in Domain.withNewTransaction
  2. Test OK ✅
  3. Modify UtilisateurRole to add constraints with withNewSession
  4. FAIL ❌

Environment Information

  • ~Database postgres~
  • ~jdbc connector version : 42.7.8~

Example Application

https://github.com/Noirtam/grails-grails702-issue15224

Version

7.0.0 / 7.0.2

Noirtam avatar Nov 12 '25 11:11 Noirtam

I'm saving User + Role + UserRole without issue locally. Can you please provide a sample project? I'm assuming something is fetching this in your UserRole domain class?

jdaugherty avatar Nov 20 '25 00:11 jdaugherty

I created a new project to reproduce the issue: https://github.com/Noirtam/grails-grails702-issue15224

When I created the new project, I found the cause of the issue. See the constraints in the "UtilisateurRole" domain :

static constraints = {
        role validator: { Role r, UtilisateurRole ur ->
            if (ur.utilisateur?.id) {
                //Issue's cause : withNewSession
                UtilisateurRole.withNewSession {
                    if (UtilisateurRole.exists(ur.utilisateur.id, r.id)) {
                        return ['userRole.exists']
                    }
                }
            }
        }
    }

UtilisateurRole.withNewSession added to resolve "No session" error

Noirtam avatar Nov 20 '25 14:11 Noirtam