7.0.0 - Domain objects are automatically inserted when entity is fetched not in a session
- Dominant language
- Groovy
- Stars
- 2.9k
- Forks
- 975
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 92
Description
```groovy
class User {
String id
static mapping = {
id generator: 'assigned'
}
}
```
```groovy
def graeme = new User()
graeme.id = 'graeme'
graeme.save(flush:true)
def user = User.get('graeme')
user.save(flush:true, insert:false) // results in BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection ..
```
This is caused because there is no common session.
https://github.com/grails/grails-data-mongodb/blob/c8287aadad3777f308ff625096171c24f0eebaf4/grails-datastore-gorm-mongodb/src/main/groovy/org/grails/datastore/mapping/mongo/engine/MongoCodecEntityPersister.groovy#L186-L188
https://github.com/grails/grails-data-mongodb/blob/c8287aadad3777f308ff625096171c24f0eebaf4/grails-datastore-gorm-mongodb/src/main/groovy/org/grails/datastore/mapping/mongo/engine/MongoCodecEntityPersister.groovy#L255-L257
returns false because `session.contains(obj)` returns **false**
The following resolves the situation, but it is not intuitive.
```groovy
User.withSession {
def user = User.get('graeme')
user.save(flush:true, insert:false)
}
```
Contributor guide
Research direction
Reproduce the provided User example, then inspect MongoCodecEntityPersister.groovy around lines 186-188 and 255-257, focusing on the session.contains(obj) checks. Trace how User.get behaves without a shared session and compare it with the User.withSession example. Done means saving a fetched entity outside a common session no longer attempts a duplicate insert.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- groovy, mongodb
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100