Skip to content

Commit

Permalink
HHH-15479 Add Results#addUnique(R result)
Browse files Browse the repository at this point in the history
  • Loading branch information
dreab8 committed Dec 7, 2022
1 parent 276be4a commit 59ffdc8
Showing 1 changed file with 27 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@
package org.hibernate.sql.results.spi;

import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.util.collections.IdentitySet;
import org.hibernate.query.ResultListTransformer;
import org.hibernate.query.spi.QueryOptions;
import org.hibernate.sql.results.internal.RowProcessingStateStandardImpl;
Expand Down Expand Up @@ -115,7 +114,7 @@ public Results(JavaType resultJavaType) {
this.resultJavaType = resultJavaType;
}

public boolean contains(R result) {
private boolean contains(R result) {
for ( int i = 0; i < results.size(); i++ ) {
if ( resultJavaType.areEqual( results.get( i ), result ) ) {
return true;
Expand All @@ -124,6 +123,14 @@ public boolean contains(R result) {
return false;
}

public boolean addUnique(R result) {
if ( contains( result ) ) {
return false;
}
results.add( result );
return true;
}

public void add(R result) {
results.add( result );
}
Expand All @@ -134,20 +141,22 @@ public List<R> getResults() {
}

private static class EntityResult<R> extends Results<R> {
private final Set<R> added = new IdentitySet<>();
private static final Object DUMP_VALUE = new Object();

private final IdentityHashMap<R, Object> added = new IdentityHashMap<>();

public EntityResult(JavaType resultJavaType) {
super( resultJavaType );
}

public boolean contains(R result) {
return added.contains( result );
public boolean addUnique(R result) {
if ( added.put( result, DUMP_VALUE ) == null ) {
super.add( result );
return true;
}
return false;
}

public void add(R result) {
super.add( result );
added.add( result );
}
}

@Override
Expand Down Expand Up @@ -263,19 +272,14 @@ private static <R> void withDuplicationCheck(
Results<R> results,
RowProcessingStateStandardImpl rowProcessingState,
boolean throwException) {
if ( results.contains( result ) ) {
if ( throwException && !rowProcessingState.hasCollectionInitializers ) {
throw new HibernateException(
String.format(
Locale.ROOT,
"Duplicate row was found and `%s` was specified",
UniqueSemantic.ASSERT
)
);
}
}
else {
results.add( result );
if ( !results.addUnique( result ) && throwException && !rowProcessingState.hasCollectionInitializers ) {
throw new HibernateException(
String.format(
Locale.ROOT,
"Duplicate row was found and `%s` was specified",
UniqueSemantic.ASSERT
)
);
}
}

Expand Down

0 comments on commit 59ffdc8

Please sign in to comment.