HHH-18492 add Hibernate.isEmpty() for pure convenience

HHH-18492 add Hibernate.isEmpty() for pure convenience

Signed-off-by: Gavin King <gavin@hibernate.org>
This commit is contained in:
Gavin King 2024-09-08 23:07:16 +02:00 committed by GitHub
parent 349b209deb
commit 04b8d80125
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 29 additions and 14 deletions

View File

@ -190,6 +190,21 @@ public final class Hibernate {
: collection.size();
}
/**
* Determine is the given persistent collection is {@linkplain Collection#isEmpty() empty},
* without fetching its state from the database.
*
* @param collection a persistent collection associated with an open session
* @return {@code true} if the collection is empty
*
* @since 7.0
*/
public static boolean isEmpty(Collection<?> collection) {
return collection instanceof PersistentCollection
? ((PersistentCollection<?>) collection).getSize() == 0
: collection.isEmpty();
}
/**
* Determine if the given persistent collection {@linkplain Collection#contains(Object) contains}
* the given element, without fetching its state from the database.

View File

@ -175,22 +175,24 @@ public abstract class AbstractPersistentCollection<E> implements Serializable, P
return false;
}
public int getSize() {
public int getSize() {
if ( cachedSize>=0 ) {
return cachedSize;
}
final CollectionEntry entry = session.getPersistenceContextInternal().getCollectionEntry( this );
if ( entry == null ) {
throwLazyInitializationExceptionIfNotConnected();
throwLazyInitializationException("collection not associated with session");
throw new AssertionFailure("impossible");
}
else {
if ( hasQueuedOperations() ) {
session.flush();
final CollectionEntry entry = session.getPersistenceContextInternal().getCollectionEntry( this );
if ( entry == null ) {
throwLazyInitializationExceptionIfNotConnected();
throwLazyInitializationException("collection not associated with session");
throw new AssertionFailure("impossible");
}
else {
if ( hasQueuedOperations() ) {
session.flush();
}
cachedSize = entry.getLoadedPersister().getSize( entry.getLoadedKey(), session );
return cachedSize;
}
cachedSize = entry.getLoadedPersister().getSize( entry.getLoadedKey(), session );
return cachedSize;
}
}

View File

@ -1383,9 +1383,7 @@ public abstract class AbstractCollectionPersister
public int getSize(Object key, SharedSessionContractImplementor session) {
try {
final JdbcCoordinator jdbcCoordinator = session.getJdbcCoordinator();
PreparedStatement st = jdbcCoordinator
.getStatementPreparer()
.prepareStatement( sqlSelectSizeString );
final PreparedStatement st = jdbcCoordinator.getStatementPreparer().prepareStatement( sqlSelectSizeString );
try {
getKeyType().nullSafeSet( st, key, 1, session );
ResultSet rs = jdbcCoordinator.getResultSetReturn().extract( st, sqlSelectSizeString );