Skip to content

Commit 5a04c37

Browse files
committed
HHH-18645 Handle proxies when resolving from existing entity in batch initializer
1 parent eaf0ba3 commit 5a04c37

File tree

4 files changed

+254
-19
lines changed

4 files changed

+254
-19
lines changed

hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/AbstractBatchEntitySelectFetchInitializer.java

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,8 @@
1010
import org.hibernate.FetchNotFoundException;
1111
import org.hibernate.Hibernate;
1212
import org.hibernate.annotations.NotFoundAction;
13-
import org.hibernate.engine.spi.EntityHolder;
14-
import org.hibernate.engine.spi.EntityKey;
15-
import org.hibernate.engine.spi.PersistenceContext;
16-
import org.hibernate.engine.spi.SharedSessionContractImplementor;
13+
import org.hibernate.bytecode.enhance.spi.interceptor.EnhancementAsProxyLazinessInterceptor;
14+
import org.hibernate.engine.spi.*;
1715
import org.hibernate.metamodel.mapping.AttributeMapping;
1816
import org.hibernate.metamodel.mapping.EntityMappingType;
1917
import org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping;
@@ -31,7 +29,9 @@
3129

3230
import org.checkerframework.checker.nullness.qual.Nullable;
3331

32+
import static org.hibernate.engine.internal.ManagedTypeHelper.isPersistentAttributeInterceptable;
3433
import static org.hibernate.proxy.HibernateProxy.extractLazyInitializer;
34+
import static org.hibernate.sql.results.graph.entity.internal.EntityInitializerImpl.getAttributeInterceptor;
3535

3636
public abstract class AbstractBatchEntitySelectFetchInitializer<Data extends AbstractBatchEntitySelectFetchInitializer.AbstractBatchEntitySelectFetchInitializerData>
3737
extends EntitySelectFetchInitializer<Data> implements EntityInitializer<Data> {
@@ -111,6 +111,10 @@ public void resolveInstance(Data data) {
111111
return;
112112
}
113113
}
114+
resolveInstanceFromIdentifier( data );
115+
}
116+
117+
protected void resolveInstanceFromIdentifier(Data data) {
114118
if ( data.batchDisabled ) {
115119
initialize( data );
116120
}
@@ -137,21 +141,36 @@ public void resolveInstance(Object instance, Data data) {
137141
// Only need to extract the identifier if the identifier has a many to one
138142
final LazyInitializer lazyInitializer = extractLazyInitializer( instance );
139143
data.entityKey = null;
144+
data.entityIdentifier = null;
140145
if ( lazyInitializer == null ) {
141-
// Entity is initialized
142-
data.setState( State.INITIALIZED );
143-
if ( keyIsEager ) {
146+
// Entity is most probably initialized
147+
data.setInstance( instance );
148+
final PersistentAttributeInterceptor interceptor;
149+
if ( concreteDescriptor.getBytecodeEnhancementMetadata().isEnhancedForLazyLoading()
150+
&& isPersistentAttributeInterceptable( instance )
151+
&& ( interceptor = getAttributeInterceptor( instance ) ) instanceof EnhancementAsProxyLazinessInterceptor ) {
152+
final EnhancementAsProxyLazinessInterceptor enhancementInterceptor = (EnhancementAsProxyLazinessInterceptor) interceptor;
153+
if ( enhancementInterceptor.isInitialized() ) {
154+
data.setState( State.INITIALIZED );
155+
}
156+
else {
157+
data.setState( State.RESOLVED );
158+
data.entityIdentifier = enhancementInterceptor.getIdentifier();
159+
}
160+
}
161+
else {
162+
// If the entity initializer is null, we know the entity is fully initialized,
163+
// otherwise it will be initialized by some other initializer
164+
data.setState( State.RESOLVED );
165+
data.entityIdentifier = concreteDescriptor.getIdentifier( instance, rowProcessingState.getSession() );
166+
}
167+
if ( keyIsEager && data.entityIdentifier == null ) {
144168
data.entityIdentifier = concreteDescriptor.getIdentifier( instance, rowProcessingState.getSession() );
145169
}
146-
data.setInstance( instance );
147170
}
148171
else if ( lazyInitializer.isUninitialized() ) {
149172
data.setState( State.RESOLVED );
150-
if ( keyIsEager ) {
151-
data.entityIdentifier = lazyInitializer.getIdentifier();
152-
}
153-
// Resolve and potentially create the entity instance
154-
registerToBatchFetchQueue( data );
173+
data.entityIdentifier = lazyInitializer.getIdentifier();
155174
}
156175
else {
157176
// Entity is initialized
@@ -161,6 +180,10 @@ else if ( lazyInitializer.isUninitialized() ) {
161180
}
162181
data.setInstance( lazyInitializer.getImplementation() );
163182
}
183+
184+
if ( data.getState() == State.RESOLVED ) {
185+
resolveInstanceFromIdentifier( data );
186+
}
164187
if ( keyIsEager ) {
165188
final Initializer<?> initializer = keyAssembler.getInitializer();
166189
assert initializer != null;

hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/BatchEntitySelectFetchInitializer.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,17 @@ protected InitializerData createInitializerData(RowProcessingState rowProcessing
6767
protected void registerResolutionListener(BatchEntitySelectFetchInitializerData data) {
6868
final RowProcessingState rowProcessingState = data.getRowProcessingState();
6969
final InitializerData owningData = owningEntityInitializer.getData( rowProcessingState );
70+
HashMap<EntityKey, List<ParentInfo>> toBatchLoad = data.toBatchLoad;
71+
if ( toBatchLoad == null ) {
72+
toBatchLoad = data.toBatchLoad = new HashMap<>();
73+
}
74+
// Always register the entity key for resolution
75+
final List<ParentInfo> parentInfos = toBatchLoad.computeIfAbsent( data.entityKey, key -> new ArrayList<>() );
7076
final AttributeMapping parentAttribute;
77+
// But only add the parent info if the parent entity is not already initialized
7178
if ( owningData.getState() != State.INITIALIZED
7279
&& ( parentAttribute = parentAttributes[owningEntityInitializer.getConcreteDescriptor( owningData ).getSubclassId()] ) != null ) {
73-
HashMap<EntityKey, List<ParentInfo>> toBatchLoad = data.toBatchLoad;
74-
if ( toBatchLoad == null ) {
75-
toBatchLoad = data.toBatchLoad = new HashMap<>();
76-
}
77-
toBatchLoad.computeIfAbsent( data.entityKey, key -> new ArrayList<>() ).add(
80+
parentInfos.add(
7881
new ParentInfo(
7982
owningEntityInitializer.getTargetInstance( owningData ),
8083
parentAttribute.getStateArrayPosition()

hibernate-core/src/main/java/org/hibernate/sql/results/graph/entity/internal/EntityInitializerImpl.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1779,7 +1779,7 @@ protected void forEachSubInitializer(BiConsumer<Initializer<?>, RowProcessingSta
17791779
}
17801780
}
17811781

1782-
private static PersistentAttributeInterceptor getAttributeInterceptor(Object entity) {
1782+
public static PersistentAttributeInterceptor getAttributeInterceptor(Object entity) {
17831783
return asPersistentAttributeInterceptable( entity ).$$_hibernate_getInterceptor();
17841784
}
17851785

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/*
2+
* Hibernate, Relational Persistence for Idiomatic Java
3+
*
4+
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
5+
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
6+
*/
7+
package org.hibernate.orm.test.bytecode.enhancement.batch;
8+
9+
import jakarta.persistence.CascadeType;
10+
import jakarta.persistence.Column;
11+
import jakarta.persistence.Entity;
12+
import jakarta.persistence.FetchType;
13+
import jakarta.persistence.GeneratedValue;
14+
import jakarta.persistence.Id;
15+
import jakarta.persistence.JoinColumn;
16+
import jakarta.persistence.ManyToOne;
17+
import jakarta.persistence.OneToMany;
18+
import jakarta.persistence.OneToOne;
19+
import jakarta.persistence.Table;
20+
import org.hibernate.Hibernate;
21+
import org.hibernate.annotations.BatchSize;
22+
import org.hibernate.cfg.AvailableSettings;
23+
import org.hibernate.graph.GraphSemantic;
24+
import org.hibernate.testing.bytecode.enhancement.extension.BytecodeEnhanced;
25+
import org.hibernate.testing.orm.junit.DomainModel;
26+
import org.hibernate.testing.orm.junit.JiraKey;
27+
import org.hibernate.testing.orm.junit.ServiceRegistry;
28+
import org.hibernate.testing.orm.junit.SessionFactory;
29+
import org.hibernate.testing.orm.junit.SessionFactoryScope;
30+
import org.hibernate.testing.orm.junit.Setting;
31+
import org.junit.jupiter.api.AfterEach;
32+
import org.junit.jupiter.api.BeforeEach;
33+
import org.junit.jupiter.api.Test;
34+
35+
import java.util.ArrayList;
36+
import java.util.List;
37+
38+
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
39+
40+
@DomainModel(
41+
annotatedClasses = {
42+
BatchLazyProxyTest.User.class,
43+
BatchLazyProxyTest.UserInfo.class,
44+
BatchLazyProxyTest.Phone.class,
45+
}
46+
47+
)
48+
@SessionFactory
49+
@ServiceRegistry(
50+
settings = {
51+
@Setting(name = AvailableSettings.DEFAULT_BATCH_FETCH_SIZE, value = "100")
52+
53+
}
54+
)
55+
@JiraKey("HHH-18645")
56+
@BytecodeEnhanced(runNotEnhancedAsWell = true)
57+
public class BatchLazyProxyTest {
58+
59+
@BeforeEach
60+
public void setUp(SessionFactoryScope scope) {
61+
scope.inTransaction(
62+
session -> {
63+
UserInfo info = new UserInfo( "info" );
64+
Phone phone = new Phone( "123456" );
65+
info.addPhone( phone );
66+
User user = new User( 1L, "user1", info );
67+
session.persist( user );
68+
}
69+
);
70+
}
71+
72+
@AfterEach
73+
public void tearDown(SessionFactoryScope scope) {
74+
scope.inTransaction(
75+
session -> {
76+
session.createMutationQuery( "delete User" ).executeUpdate();
77+
session.createMutationQuery( "delete Phone" ).executeUpdate();
78+
session.createMutationQuery( "delete UserInfo" ).executeUpdate();
79+
}
80+
);
81+
}
82+
83+
@Test
84+
public void testBatchInitialize(SessionFactoryScope scope) {
85+
scope.inTransaction(
86+
session -> {
87+
User user = session.createQuery( "select u from User u where u.id = :id", User.class )
88+
.setEntityGraph( session.createEntityGraph( User.class ), GraphSemantic.FETCH )
89+
.setParameter( "id", 1L )
90+
.getSingleResult();
91+
assertThat( Hibernate.isInitialized( user.getInfo() ) ).isFalse();
92+
session.createQuery( "select u from User u where u.id = :id", User.class )
93+
.setParameter( "id", 1L )
94+
.getSingleResult();
95+
assertThat( Hibernate.isInitialized( user.getInfo() ) ).isTrue();
96+
}
97+
);
98+
}
99+
100+
@Entity(name = "User")
101+
@Table(name = "USER_TABLE")
102+
@BatchSize(size = 5)
103+
public static class User {
104+
105+
@Id
106+
private Long id;
107+
108+
@Column
109+
private String name;
110+
111+
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
112+
@JoinColumn(name = "INFO_ID", referencedColumnName = "ID")
113+
private UserInfo info;
114+
115+
public User() {
116+
}
117+
118+
public User(long id, String name, UserInfo info) {
119+
this.id = id;
120+
this.name = name;
121+
this.info = info;
122+
info.user = this;
123+
}
124+
125+
public long getId() {
126+
return id;
127+
}
128+
129+
public String getName() {
130+
return name;
131+
}
132+
133+
public UserInfo getInfo() {
134+
return info;
135+
}
136+
}
137+
138+
@Entity(name = "UserInfo")
139+
public static class UserInfo {
140+
@Id
141+
@GeneratedValue
142+
private Long id;
143+
144+
@OneToOne(mappedBy = "info", fetch = FetchType.LAZY)
145+
private User user;
146+
147+
private String info;
148+
149+
@OneToMany(mappedBy = "info", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
150+
private List<Phone> phoneList;
151+
152+
public long getId() {
153+
return id;
154+
}
155+
156+
public UserInfo() {
157+
}
158+
159+
public UserInfo(String info) {
160+
this.info = info;
161+
}
162+
163+
public User getUser() {
164+
return user;
165+
}
166+
167+
public String getInfo() {
168+
return info;
169+
}
170+
171+
public List<Phone> getPhoneList() {
172+
return phoneList;
173+
}
174+
175+
public void addPhone(Phone phone) {
176+
if ( phoneList == null ) {
177+
phoneList = new ArrayList<>();
178+
}
179+
this.phoneList.add( phone );
180+
phone.info = this;
181+
}
182+
}
183+
184+
@Entity(name = "Phone")
185+
public static class Phone {
186+
@Id
187+
@Column(name = "PHONE_NUMBER")
188+
private String number;
189+
190+
@ManyToOne
191+
@JoinColumn(name = "INFO_ID")
192+
private UserInfo info;
193+
194+
public Phone() {
195+
}
196+
197+
public Phone(String number) {
198+
this.number = number;
199+
}
200+
201+
public String getNumber() {
202+
return number;
203+
}
204+
205+
public UserInfo getInfo() {
206+
return info;
207+
}
208+
}
209+
}

0 commit comments

Comments
 (0)