@Override public Object[] load(EntityInfo entityInfo) { Object[] projection = entityInfo.getProjection(); if (stream(projection).anyMatch(o -> o == EntityInfo.ENTITY_PLACEHOLDER)) { entityInfo.populateWithEntityInstance(entityLoader.load(entityInfo)); } return projectionConverter.convert(projection); } }
@Override protected final List executeLoad(List<EntityInfo> entityInfos) { if ( entityType == null ) { throw new AssertionFailure( "EntityType not defined" ); } LinkedHashMap<EntityInfoLoadKey, Object> idToObjectMap = new LinkedHashMap<>( (int) ( entityInfos.size() / 0.75 ) + 1 ); for ( EntityInfo entityInfo : entityInfos ) { idToObjectMap.put( new EntityInfoLoadKey( entityInfo.getType().getPojoType(), entityInfo.getId() ), ObjectInitializer.ENTITY_NOT_YET_INITIALIZED ); } objectInitializer.initializeObjects( entityInfos, idToObjectMap, new ObjectInitializationContext( criteria, entityType, extendedIntegrator, timeoutManager, session ) ); ArrayList<Object> result = new ArrayList<>( idToObjectMap.size() ); for ( Object o : idToObjectMap.values() ) { if ( o != ObjectInitializer.ENTITY_NOT_YET_INITIALIZED ) { result.add( o ); } } return result; }
private boolean areAllEntitiesManaged(Object[] objects, EntityInfo entityInfo) { //check if all entities are session-managed and skip the check on projected values org.hibernate.Session hibSession = (org.hibernate.Session) session; if ( entityInfo.getProjection() != null ) { if ( hasThisProjection ) { // using projection: test only for entities Object entity = entityInfo.getEntityInstance(); if ( entity != null ) { //TODO improve: is it useful to check for proxies and have them reassociated to persistence context? return hibSession.contains( entity ); } } return true; } else { return hibSession.contains( objects[0] ); } }
private static Object executeLoad(EntityInfo entityInfo, SessionImplementor session) { Object maybeProxy; if ( areDocIdAndEntityIdIdentical( entityInfo, session ) ) { // be sure to get an initialized object but save from ObjectNotFoundException and EntityNotFoundException maybeProxy = session.byId( entityInfo.getType().getPojoType() ).load( entityInfo.getId() ); } else { Criteria criteria = new CriteriaImpl( entityInfo.getType().getName(), (SharedSessionContractImplementor) session ); criteria.add( Restrictions.eq( entityInfo.getIdName(), entityInfo.getId() ) ); try { maybeProxy = criteria.uniqueResult(); } catch (HibernateException e) { // FIXME should not raise an exception but return something like null // FIXME this happens when the index is out of sync with the db) throw new SearchException( "Loading entity of type " + entityInfo.getType().getName() + " using '" + entityInfo.getIdName() + "' as document id and '" + entityInfo.getId() + "' as value was not unique" ); } } return maybeProxy; }
@Test @TestForIssue(jiraKey = "HSEARCH-1987") public void testNumericMappingOfEmbeddedFields() { List<EntityInfo> list = helper.hsQuery( ScoreBoard.class ) .projection( ProjectionConstants.DOCUMENT ) .queryEntityInfos(); assertEquals( 1, list.size() ); Document document = (Document) list.iterator().next().getProjection()[0]; IndexableField scoreNumeric = document.getField( "score_id" ); assertThat( scoreNumeric.numericValue() ).isEqualTo( 1 ); IndexableField beta = document.getField( "score_beta" ); assertThat( beta.numericValue() ).isEqualTo( 100 ); }
private Object decodeKey(EntityInfo entityInfo) { return keyTransformationHandler.stringToKey(entityInfo.getId().toString()); }
public static boolean areDocIdAndEntityIdIdentical(EntityInfo entityInfo, SessionImplementor session) { SessionFactoryImplementor sessionFactoryImplementor = session.getSessionFactory(); ClassMetadata cm = sessionFactoryImplementor.getMetamodel().entityPersister( entityInfo.getType().getName() ).getClassMetadata(); String hibernateIdentifierProperty = cm.getIdentifierPropertyName(); return entityInfo.getIdName().equals( hibernateIdentifierProperty ); } }
return (Integer) entityInfos.iterator().next().getProjection()[0];
private Object decodeKey(EntityInfo entityInfo) { return keyTransformationHandler.stringToKey(entityInfo.getId().toString(), cache.getClassLoader()); }
public Object[] load(EntityInfo entityInfo) { Object[] projection = entityInfo.getProjection(); if (stream(projection).anyMatch(o -> o == EntityInfo.ENTITY_PLACEHOLDER)) { entityInfo.populateWithEntityInstance(entityLoader.load(entityInfo)); } return projectionConverter.convert(projection); } }
@Test @TestForIssue(jiraKey = "HSEARCH-1987") public void testOneOfSeveralFieldsIsNumeric() { List<EntityInfo> list = helper.hsQuery( TouristAttraction.class ) .projection( ProjectionConstants.DOCUMENT ) .queryEntityInfos(); assertEquals( 1, list.size() ); Document document = (Document) list.iterator().next().getProjection()[0]; IndexableField scoreNumeric = document.getField( "scoreNumeric" ); assertThat( scoreNumeric.numericValue() ).isEqualTo( 23 ); IndexableField scoreString = document.getField( "scoreString" ); assertThat( scoreString.numericValue() ).isNull(); assertThat( scoreString.stringValue() ).isEqualTo( "23" ); }
/** * Returns a {@link Criterion} for fetching all the given entity infos. If needed, this criterion will contain a * {@link Disjunction} for fetching the infos in chunks of {@link CriteriaObjectInitializer#MAX_IN_CLAUSE} elements. */ private Criterion getIdListCriterion(List<EntityInfo> entityInfos, ObjectInitializationContext objectInitializationContext) { DocumentBuilderIndexedEntity documentBuilder = getDocumentBuilder( entityInfos.iterator().next().getType(), objectInitializationContext.getExtendedSearchIntegrator() ); String idName = documentBuilder.getIdPropertyName(); Disjunction disjunction = Restrictions.disjunction(); int maxResults = entityInfos.size(); int loop = maxResults / MAX_IN_CLAUSE; boolean exact = maxResults % MAX_IN_CLAUSE == 0; if ( !exact ) { loop++; } for ( int index = 0; index < loop; index++ ) { int max = Math.min( index * MAX_IN_CLAUSE + MAX_IN_CLAUSE, maxResults ); List<Serializable> ids = new ArrayList<>( max - index * MAX_IN_CLAUSE ); for ( int entityInfoIndex = index * MAX_IN_CLAUSE; entityInfoIndex < max; entityInfoIndex++ ) { ids.add( entityInfos.get( entityInfoIndex ).getId() ); } disjunction.add( Restrictions.in( idName, ids ) ); } return disjunction; }
/** * Utility to extract the cache key of a DocumentExtractor and use the KeyTransformationHandler to turn the string * into the actual key object. * * @param extractor * @param docIndex * @return */ Object extractKey(DocumentExtractor extractor, int docIndex) { String strKey; try { strKey = (String) extractor.extract(docIndex).getId(); } catch (IOException e) { throw new SearchException("Error while extracting key", e); } return keyTransformationHandler.stringToKey(strKey); } }
@Override public Object load(EntityInfo entityInfo) { //no need to timeouManage here, the underlying loader is the real time consumer if ( projectThis ) { Loader objectLoader = getObjectLoader(); final Object entityInstance = objectLoader.load( entityInfo ); entityInfo.populateWithEntityInstance( entityInstance ); } if ( transformer != null ) { return transformer.transformTuple( entityInfo.getProjection(), aliases ); } else { return entityInfo.getProjection(); } }
return (Integer) entityInfos.iterator().next().getProjection()[0];
for ( EntityInfo entityInfo : entityInfos ) { boolean found = false; final Class<?> clazz = entityInfo.getType().getPojoType(); for ( RootEntityMetadata rootEntityInfo : entityMetadata ) { if ( rootEntityInfo.rootEntity == clazz || rootEntityInfo.mappedSubclasses.contains( clazz ) ) { found = true; idToObjectMap.put( new EntityInfoLoadKey( entityInfo.getType().getPojoType(), entityInfo.getId() ), ObjectInitializer.ENTITY_NOT_YET_INITIALIZED );
public static Object extractKey(DocumentExtractor extractor, Cache<?, ?> cache, KeyTransformationHandler keyTransformationHandler, int docIndex) { String bufferDocumentId; try { bufferDocumentId = (String) extractor.extract(docIndex).getId(); } catch (IOException e) { log.error("Error while extracting key...", e); return null; } Object key = keyTransformationHandler.stringToKey(bufferDocumentId, cache .getAdvancedCache().getClassLoader()); return key; }
@Override public List load(List<EntityInfo> entityInfos) { //no need to timeouManage here, the underlying loader is the real time consumer List results = new ArrayList( entityInfos.size() ); if ( entityInfos.isEmpty() ) { return results; } if ( projectThis ) { Loader objectLoader = getObjectLoader(); objectLoader.load( entityInfos ); // load by batch for ( EntityInfo entityInfo : entityInfos ) { final Object entityInstance = objectLoader.loadWithoutTiming( entityInfo ); entityInfo.populateWithEntityInstance( entityInstance ); } } for ( EntityInfo entityInfo : entityInfos ) { if ( transformer != null ) { results.add( transformer.transformTuple( entityInfo.getProjection(), aliases ) ); } else { results.add( entityInfo.getProjection() ); } } if ( transformer != null ) { return transformer.transformList( results ); } return results; }
private NodeTopDocs collectKeys(DocumentExtractor extractor, HSQuery query) { TopDocs topDocs = extractor.getTopDocs(); int topDocsLength = topDocs.scoreDocs.length; Object[] keys = null; Object[] projections = null; if (query.getProjectedFields() == null) { keys = new Object[topDocsLength]; // collecting keys (it's a eager query!) for (int i = 0; i < topDocsLength; i++) { keys[i] = extractKey(extractor, i); } } else { projections = new Object[topDocsLength]; try { for (int docIndex = 0; docIndex < topDocsLength; docIndex++) { projections[docIndex] = extractor.extract(docIndex).getProjection(); } } catch (IOException e) { throw new SearchException("Error while extracting projection", e); } } return new NodeTopDocs(cache.getRpcManager().getAddress(), topDocs, keys, projections); } }
@Override public void initializeObjects(List<EntityInfo> entityInfos, LinkedHashMap<EntityInfoLoadKey, Object> idToObjectMap, ObjectInitializationContext objectInitializationContext) { boolean traceEnabled = log.isTraceEnabled(); // Do not call isTimeOut here as the caller might be the last biggie on the list. final int maxResults = entityInfos.size(); if ( maxResults == 0 ) { if ( traceEnabled ) { log.tracef( "No object to initialize" ); } return; } for ( EntityInfo entityInfo : entityInfos ) { Object o = ObjectLoaderHelper.load( entityInfo, objectInitializationContext.getSession() ); if ( o != null ) { EntityInfoLoadKey key = new EntityInfoLoadKey( entityInfo.getType().getPojoType(), entityInfo.getId() ); idToObjectMap.put( key, o ); } } if ( traceEnabled ) { log.tracef( "Initialized %d objects by lookup method.", (Integer) maxResults ); } } }