Repository navigation
fix(hibernate5): merge writes the changed fields of a detached instance, criterion in junction #16845
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(hibernate5): merge writes the changed fields of a detached instance, criterion in junction #16845
Changes from all commits
4737032
6a67abe
e03a88c
7cc3250
1e97952
de4deaa
d9cdbf8
7431c6c
3e2c168
793a1ad
f7f1fc8
461f9f7
1375c4c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,6 +31,7 @@ import org.hibernate.LockMode | |
| import org.hibernate.Session | ||
| import org.hibernate.SessionFactory | ||
| import org.hibernate.collection.spi.PersistentCollection | ||
| import org.hibernate.engine.internal.ForeignKeys | ||
| import org.hibernate.engine.spi.CascadeStyle | ||
| import org.hibernate.engine.spi.CascadingActions | ||
| import org.hibernate.engine.spi.SessionImplementor | ||
|
|
@@ -451,8 +452,27 @@ abstract class AbstractHibernateGormInstanceApi<D> extends GormInstanceApi<D> { | |
| } | ||
|
|
||
| protected D performMerge(final D target, final boolean flush) { | ||
| // Hibernate copies the state of a detached instance onto the managed one without GORM's change tracking | ||
| // seeing it, so the properties the detached instance changed are marked on the managed one; otherwise | ||
| // the dirtiness strategy finds nothing to flush. | ||
| List<String> changed = target instanceof DirtyCheckable ? ((DirtyCheckable) target).listDirtyPropertyNames() : [] | ||
| // a detached instance that reports a change without naming the properties, such as one restored from a | ||
| // serialized session, has all of its properties marked | ||
| boolean changedWithoutNames = changed.isEmpty() && target instanceof DirtyCheckable && | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A new instance whose id is a primitive long is 0, so this treats it as detached. After the insert, the managed copy is marked dirty and the flush issues an update. A new instance that already tracks a named change takes the other branch and is marked dirty the same way. Leave a new instance alone after the insert. |
||
| ((DirtyCheckable) target).hasChanged() | ||
| hibernateTemplate.execute { Session session -> | ||
| // Hibernate's own test for an instance that merge() inserts: the id and version unsaved values, and for | ||
| // an id it cannot judge a look at the row. A new instance is left alone after the insert, whatever id | ||
| // type it has and whatever changes it tracks. | ||
| boolean inserted = ForeignKeys.isTransient(target.getClass().name, target, null, (SessionImplementor) session) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Book.merge(bookProxy) used to merge the proxy. It now throws, because the proxy class is not a mapped name. A new instance with an assigned identifier and a version is inserted and then updated. Unwrap a proxy before this check, and do not mark a row that was just inserted. |
||
| Object merged = session.merge(target) | ||
| if (!inserted && merged instanceof DirtyCheckable && !merged.is(target)) { | ||
| if (changedWithoutNames) { | ||
| ((DirtyCheckable) merged).markDirty() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. new MergeDirtyData(name: 'new', number: 1).merge(flush: true) inserts the row and then updates it. The version goes from 0 to 1. A new instance has no named dirty properties, so this marks the merged copy dirty after the insert. Leave a new instance alone after the insert. |
||
| } else { | ||
| changed.each { String name -> ((DirtyCheckable) merged).markDirty(name) } | ||
| } | ||
| } | ||
| session.lock(merged, LockMode.NONE) | ||
| if (flush) { | ||
| flushSession(session) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package grails.gorm.tests | ||
|
|
||
| import grails.gorm.annotation.Entity | ||
| import org.hibernate.criterion.Restrictions | ||
| import spock.lang.Issue | ||
|
|
||
| @Issue('https://github.com/apache/grails-core/issues/14370') | ||
| class HibernateCriterionInJunctionSpec extends HibernateGormDatastoreSpec { | ||
|
|
||
| void setupSpec() { | ||
| manager.registerDomainClasses(JunctionAuthor) | ||
| } | ||
|
|
||
| void setup() { | ||
| ['author1', 'author2', 'author3'].each { new JunctionAuthor(authorName: it).save() } | ||
| session.flush() | ||
| session.clear() | ||
| } | ||
|
|
||
| void "a Hibernate criterion added inside or is part of the disjunction"() { | ||
| given: | ||
| Long id1 = JunctionAuthor.findByAuthorName('author1').id | ||
|
|
||
| expect: | ||
| JunctionAuthor.createCriteria().list { | ||
| or { | ||
| add Restrictions.eq('authorName', 'author2') | ||
| eq 'id', id1 | ||
| } | ||
| order 'authorName' | ||
| }*.authorName == ['author1', 'author2'] | ||
| } | ||
|
|
||
| void "a Hibernate criterion added inside and is part of the conjunction"() { | ||
| expect: | ||
| JunctionAuthor.createCriteria().list { | ||
| and { | ||
| add Restrictions.like('authorName', 'author%') | ||
| ne 'authorName', 'author3' | ||
| } | ||
| order 'authorName' | ||
| }*.authorName == ['author1', 'author2'] | ||
| } | ||
|
|
||
| void "a Hibernate criterion added inside not is negated"() { | ||
| expect: | ||
| JunctionAuthor.createCriteria().list { | ||
| not { | ||
| add Restrictions.eq('authorName', 'author1') | ||
| } | ||
| order 'authorName' | ||
| }*.authorName == ['author2', 'author3'] | ||
| } | ||
|
|
||
| void "add returns the Criteria at the top level, so calls chain, and the criterion it added inside a junction"() { | ||
| expect: | ||
| JunctionAuthor.createCriteria().list { | ||
| add(Restrictions.like('authorName', 'author%')).add(Restrictions.ne('authorName', 'author3')) | ||
| order 'authorName' | ||
| }*.authorName == ['author1', 'author2'] | ||
|
|
||
| when: | ||
| def added = [] | ||
| def eq1 = Restrictions.eq('authorName', 'author1') | ||
| def eq3 = Restrictions.eq('authorName', 'author3') | ||
| List found = JunctionAuthor.createCriteria().list { | ||
| or { | ||
| added << add(eq1) | ||
| added << add(eq3) | ||
| } | ||
| order 'authorName' | ||
| } | ||
|
|
||
| then: 'each call returns the criterion it added, and both are part of the disjunction' | ||
| added[0].is(eq1) | ||
| added[1].is(eq3) | ||
| found*.authorName == ['author1', 'author3'] | ||
| } | ||
|
|
||
| void "the result of add at the top level is the Criteria, so list works on it"() { | ||
| expect: | ||
| JunctionAuthor.createCriteria().add(Restrictions.like('authorName', 'author%')) | ||
| .add(Restrictions.ne('authorName', 'author3')).addOrder(org.hibernate.criterion.Order.asc('authorName')) | ||
| .list()*.authorName == ['author1', 'author2'] | ||
| } | ||
|
|
||
| void "a Hibernate criterion added at the top level still applies"() { | ||
| expect: | ||
| JunctionAuthor.createCriteria().list { | ||
| add Restrictions.eq('authorName', 'author3') | ||
| }*.authorName == ['author3'] | ||
| } | ||
| } | ||
|
|
||
| @Entity | ||
| class JunctionAuthor { | ||
| String authorName | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package grails.gorm.tests | ||
|
|
||
| import grails.gorm.annotation.Entity | ||
| import spock.lang.Issue | ||
|
|
||
| @Issue('https://github.com/apache/grails-core/issues/14354') | ||
| class MergeDetachedDirtyFieldsSpec extends HibernateGormDatastoreSpec { | ||
|
|
||
| void setupSpec() { | ||
| manager.registerDomainClasses(MergeDirtyData, MergePrimitiveIdData) | ||
| } | ||
|
|
||
| void "merge writes the changed fields of a detached instance"() { | ||
| given: | ||
| MergeDirtyData data = new MergeDirtyData(name: 'a', number: 1).save(flush: true) | ||
| session.clear() | ||
|
|
||
| when: 'the detached instance is changed and merged' | ||
| data.name = 'dirty' | ||
| data.number = 2 | ||
| MergeDirtyData merged = data.merge(flush: true) | ||
| session.clear() | ||
| MergeDirtyData reloaded = MergeDirtyData.get(data.id) | ||
|
|
||
| then: 'the merged instance and the stored row carry the changes' | ||
| merged.name == 'dirty' | ||
| reloaded.name == 'dirty' | ||
| reloaded.number == 2 | ||
| } | ||
|
|
||
| void "merge writes an instance that reports a change without naming the properties"() { | ||
| given: | ||
| MergeDirtyData data = new MergeDirtyData(name: 'a', number: 1).save(flush: true) | ||
| session.clear() | ||
|
|
||
| when: 'the instance carries the id and version of the row, is made by hand, restored from a serialized copy, or marked dirty as a whole' | ||
| MergeDirtyData instance = new MergeDirtyData(name: 'changed', number: 2) | ||
| instance.id = data.id | ||
| instance.version = data.version | ||
| if (form == 'serialized') { | ||
| instance = serialized(instance) | ||
| } else if (form == 'marked') { | ||
| instance.markDirty() | ||
| } | ||
| MergeDirtyData merged = instance.merge(flush: true) | ||
| session.clear() | ||
|
|
||
| then: 'the row carries its values' | ||
| merged.name == 'changed' | ||
| MergeDirtyData.get(data.id).name == 'changed' | ||
| MergeDirtyData.get(data.id).number == 2 | ||
|
|
||
| where: | ||
| form << ['new', 'serialized', 'marked'] | ||
| } | ||
|
|
||
| void "merge of a new instance inserts it once"() { | ||
| when: 'a new instance is merged' | ||
| MergeDirtyData merged = new MergeDirtyData(name: 'new', number: 1).merge(flush: true) | ||
|
|
||
| then: 'the insert is not followed by an update' | ||
| merged.version == 0 | ||
| MergeDirtyData.count() == 1 | ||
| } | ||
|
|
||
| void "merge of a new instance that tracks a named change is not followed by an update"() { | ||
| given: 'a new instance whose property is set after construction, so the change is tracked by name' | ||
| MergeDirtyData data = new MergeDirtyData() | ||
| data.name = 'tracked' | ||
|
|
||
| when: | ||
| MergeDirtyData merged = data.merge(flush: true) | ||
|
|
||
| then: 'the insert is the only write' | ||
| merged.version == 0 | ||
| MergeDirtyData.count() == 1 | ||
| } | ||
|
|
||
| void "merge of a new instance with a primitive id is not followed by an update"() { | ||
| when: 'the id of a new instance is the primitive default 0, not null' | ||
| MergePrimitiveIdData merged = new MergePrimitiveIdData(name: 'new').merge(flush: true) | ||
|
|
||
| then: 'it is inserted once' | ||
| merged.version == 0 | ||
| MergePrimitiveIdData.count() == 1 | ||
| } | ||
|
|
||
| void "merge of an instance the session already manages keeps its changes"() { | ||
| given: | ||
| MergeDirtyData data = new MergeDirtyData(name: 'a', number: 1).save(flush: true) | ||
|
|
||
| when: 'the instance is still attached to the session' | ||
| data.name = 'managed' | ||
| MergeDirtyData merged = data.merge(flush: true) | ||
| session.clear() | ||
|
|
||
| then: 'the merge returns the same instance and the row carries the change' | ||
| merged.is(data) | ||
| MergeDirtyData.get(data.id).name == 'managed' | ||
| } | ||
|
|
||
| private static MergeDirtyData serialized(MergeDirtyData data) { | ||
| ByteArrayOutputStream bytes = new ByteArrayOutputStream() | ||
| new ObjectOutputStream(bytes).withCloseable { ObjectOutputStream out -> out.writeObject(data) } | ||
| new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).withCloseable { ObjectInputStream input -> | ||
| (MergeDirtyData) input.readObject() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Entity | ||
| class MergeDirtyData implements Serializable { | ||
| String name | ||
| Integer number | ||
| } | ||
|
|
||
| @Entity | ||
| class MergePrimitiveIdData implements Serializable { | ||
| long id | ||
| String name | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package functional.tests | ||
|
|
||
| import grails.gorm.annotation.Entity | ||
|
|
||
| @Entity | ||
| class ScenarioOldIssueItem { | ||
|
|
||
| String name | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
listDirtyPropertyNames()is empty when GORM has no list of changed names, althoughhasChanged()is true. Nothing is then marked on the merged instance and the row keeps its old values:merge()new Foo(...)with the id of an existing rowmarkDirty()on the whole instanceThe scenario in #14354 keeps the instance in the HTTP session, and
$changedPropertiesis transient, so a session store that serializes takes the third row.Please call
markDirty()on the merged instance whenhasChanged()is true and no names are listed, and add a spec for those three rows. In a throwaway spec that change writes all three, andMergeDetachedDirtyFieldsSpecstill passes.Changes to a child cascaded from the merged parent, and to an embedded object changed in place, are not written either, on 8.0.x or here. Those need a different mechanism, so a follow-up issue is fine.