EclipseLink - Subqueries with Criteria Query (JPA) - java
take the following two tables as given:
Objects with columns objId, objTaxonId
Taxa with columns taxId, taxValidSynonymId, taxName (Note Taxa is plural for Taxon)
if a Taxon is valid, its id and validSynonymId are identical, otherwise they are different. To find all synonyms of a Taxon you 'only' need to find all Taxa where the taxValidSynonymId is filled with the taxId of the valid Taxon
how can i gain all Objects where the Taxon has a given Name (including their Synonyms?)
in SQL this is done in a few lines (and Minutes)
SELECT *
FROM Objects
WHERE objTaxonId IN (
SELECT taxId
FROM Taxa
WHERE taxName LIKE 'Test Taxon 1'
OR taxSynIdTaxon IN(
SELECT taxId
FROM Taxa
WHERE taxName LIKE 'Test Taxon 1'
)
)
i was able to work out the inside part, where i gain the list of Taxa and its Synonyms. Now i need to transform this Query to a Subquery...
String NAME_LIKE = "Test Taxon 1";
EntityManager em = EntityManagerProvider.getEntityManager("TestDB"); // get the EntityManager
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<TaxonImpl> cqObject = cb.createQuery(TaxonImpl.class);//
Root<TaxonImpl> taxonRoot = cqObject.from(TaxonImpl.class);//
Expression<String> taxon_name = taxonRoot.<String> get("taxName");
Predicate where = cb.equal(taxon_name, NAME_LIKE);
// subquery
Subquery<Integer> subQuery = cqObject.subquery(Integer.class);
Root<TaxonImpl> subRoot = subQuery.from(clsImpl);
subQuery.select(subRoot.<Integer> get("taxId"));
subQuery.where(cb.equal(subRoot.<String> get("taxName"), NAME_LIKE));
where = cb.or(where, taxonRoot.get("taxValidSynonymId").in(subQuery));
cqObject.where(where);
Query query = em.createQuery(cqObject);
List<TaxonImpl> result = query.getResultList();
NOTE: the Taxon is Mapped as an many to One relation (target-entity is TaxonImpl)
in my actual application the code (from the subquery) will be dynamically, so a Native Query does not help me.
i figured out how to "transform" the subquery into a query but Eclipselink threw me two errors
the first was forbidden access via field, when i tried the in on a result of TaxonImpl (i tried that first, as in my mapping files the Taxon is mapped as Entity.
so after this i tried to form the SQL 1:1 to JPA.
but Eclipselink generated something weird:
SELECT t0.objIdObject, t0.objAdminCreated, t0.objAdminCreator, t0.objAdminEdited, t0.objAdminEditor, t0.objAdminImport1, t0.objAdminImport2, t0.objAddBool1, t0.objAddBool2, t0.objAddBool3, t0.objAddBool4, t0.objAddBool5, t0.objAddDateTime1, t0.objAddDateTime2, t0.objCommonComments, t0.objCommonDescription, t0.objCommonKeywords, t0.objCommonName, t0.objCommonPublished, t0.objCommonPublishedAs, t0.objCommonStatus, t0.objCommonType, t0.objCommonTypustype, t0.objDetAccuracy, t0.objDetCf, t0.objDetComments, t0.objDetDate, t0.objDetMethod, t0.objDetResult, t0.objAddFloat1, t0.objAddFloat2, t0.objAddFloat3, t0.objAddFloat4, t0.objAddFloat5, t0.objEventAbundance, t0.objEventCollectionMethod, t0.objEventComments, t0.objEventMoreContacts, t0.objEventDateDay1, t0.objEventDate1, t0.objEventDateMonth1, t0.objEventDate2, t0.objEventDateUncertain, t0.objEventDateYear1, t0.objEventEcosystem, t0.objEventHabitat, t0.objEventNumber, t0.objEventPermission, t0.objEventSubstratum, t0.objEventTime1, t0.objEventTime2, t0.objEventWeekNumber, t0.objFlora, t0.objGuidObject, t0.objIOComments, t0.objIODeAccessed, t0.objAddInt1, t0.objAddInt2, t0.objAddInt3, t0.objAddInt4, t0.objAddInt5, t0.objStorageForeignNumber, t0.objStorageNumber, t0.objStorageNumberInCollection, t0.objStorageNumberOld, t0.objStorageNumberPrefix, t0.objAddLkp1, t0.objAddLkp10, t0.objAddLkp2, t0.objAddLkp3, t0.objAddLkp4, t0.objAddLkp5, t0.objAddLkp6, t0.objAddLkp7, t0.objAddLkp8, t0.objAddLkp9, t0.objAddLkpCs1, t0.objAddLkpCs10, t0.objAddLkpCs11, t0.objAddLkpCs12, t0.objAddLkpCs13, t0.objAddLkpCs14, t0.objAddLkpCs15, t0.objAddLkpCs2, t0.objAddLkpCs3, t0.objAddLkpCs4, t0.objAddLkpCs5, t0.objAddLkpCs6, t0.objAddLkpCs7, t0.objAddLkpCs8, t0.objAddLkpCs9, t0.objOriginAccessionDate, t0.objOriginAccessionNumber, t0.objOriginComments, t0.objOriginMoreContacts, t0.objOriginSource, t0.objOriginType, t0.objPreparationComments, t0.objPreparationDate, t0.objPreparationType, t0.objPropAdults, t0.objPropAge, t0.objPropAgeUnit, t0.objPropEggs, t0.objPropFemale, t0.objPropHeight, t0.objPropHeightUnit, t0.objPropJuveniles, t0.objPropLarvae, t0.objPropLength, t0.objPropLengthUnit, t0.objPropMale, t0.objPropObservation, t0.objPropObservationComments, t0.objPropPupae, t0.objPropSex, t0.objPropStadium, t0.objPropWeight, t0.objPropWeightUnit, t0.objPropWidth, t0.objPropWidthUnit, t0.objSiteComments, t0.objStorageComments, t0.objStorageContainerNumber, t0.objStorageContainerPieces, t0.objStorageContainerType, t0.objStorageLevel1, t0.objStorageLevel2, t0.objStorageLevel3, t0.objStorageLevel4, t0.objStorageLevel5, t0.objStorageNumberInContainer, t0.objstoragePieces, t0.objStorageValue, t0.objStorageValueUnit, t0.objAddText1, t0.objAddText10, t0.objAddText2, t0.objAddText3, t0.objAddText4, t0.objAddText5, t0.objAddText6, t0.objAddText7, t0.objAddText8, t0.objAddText9, t0.objIdCollection, t0.objCommonIdReference, t0.objDetIdContact, t0.objDetIdReference, t0.objEventIdContact, t0.objIdExcursion, t0.objOriginIdContact, t0.objPreparationIdContact, t0.objIdProject, t0.objSiteIdSite, t0.objdetIdTaxon
FROM tObjects t0
WHERE t0.objdetIdTaxon IN (
SELECT t1.taxIdTaxon.t1.taxIdTaxon
FROM tTaxa t1
WHERE (t1.taxTaxonDisplay LIKE 'Test Taxon 1'
OR t1.taxSynIdTaxon IN (
SELECT t2.taxSynIdTaxon
FROM tTaxa t2
WHERE t2.taxTaxonDisplay LIKE 'Test Taxon 1')))
to take out the error:
SELECT t1.taxIdTaxon.t1.taxIdTaxon
which is complete crap. you cannot execute a function on an type of int!
resolving this error (BUG?) introduces a new construct (which still returns the same results)
SELECT t1.objIdObject, t1.objAdminCreated, t1.objAdminCreator, t1.objAdminEdited, t1.objAdminEditor, t1.objAdminImport1, t1.objAdminImport2, t1.objAddBool1, t1.objAddBool2, t1.objAddBool3, t1.objAddBool4, t1.objAddBool5, t1.objAddDateTime1, t1.objAddDateTime2, t1.objCommonComments, t1.objCommonDescription, t1.objCommonKeywords, t1.objCommonName, t1.objCommonPublished, t1.objCommonPublishedAs, t1.objCommonStatus, t1.objCommonType, t1.objCommonTypustype, t1.objDetAccuracy, t1.objDetCf, t1.objDetComments, t1.objDetDate, t1.objDetMethod, t1.objDetResult, t1.objAddFloat1, t1.objAddFloat2, t1.objAddFloat3, t1.objAddFloat4, t1.objAddFloat5, t1.objEventAbundance, t1.objEventCollectionMethod, t1.objEventComments, t1.objEventMoreContacts, t1.objEventDateDay1, t1.objEventDate1, t1.objEventDateMonth1, t1.objEventDate2, t1.objEventDateUncertain, t1.objEventDateYear1, t1.objEventEcosystem, t1.objEventHabitat, t1.objEventNumber, t1.objEventPermission, t1.objEventSubstratum, t1.objEventTime1, t1.objEventTime2, t1.objEventWeekNumber, t1.objFlora, t1.objGuidObject, t1.objIOComments, t1.objIODeAccessed, t1.objAddInt1, t1.objAddInt2, t1.objAddInt3, t1.objAddInt4, t1.objAddInt5, t1.objStorageForeignNumber, t1.objStorageNumber, t1.objStorageNumberInCollection, t1.objStorageNumberOld, t1.objStorageNumberPrefix, t1.objAddLkp1, t1.objAddLkp10, t1.objAddLkp2, t1.objAddLkp3, t1.objAddLkp4, t1.objAddLkp5, t1.objAddLkp6, t1.objAddLkp7, t1.objAddLkp8, t1.objAddLkp9, t1.objAddLkpCs1, t1.objAddLkpCs10, t1.objAddLkpCs11, t1.objAddLkpCs12, t1.objAddLkpCs13, t1.objAddLkpCs14, t1.objAddLkpCs15, t1.objAddLkpCs2, t1.objAddLkpCs3, t1.objAddLkpCs4, t1.objAddLkpCs5, t1.objAddLkpCs6, t1.objAddLkpCs7, t1.objAddLkpCs8, t1.objAddLkpCs9, t1.objOriginAccessionDate, t1.objOriginAccessionNumber, t1.objOriginComments, t1.objOriginMoreContacts, t1.objOriginSource, t1.objOriginType, t1.objPreparationComments, t1.objPreparationDate, t1.objPreparationType, t1.objPropAdults, t1.objPropAge, t1.objPropAgeUnit, t1.objPropEggs, t1.objPropFemale, t1.objPropHeight, t1.objPropHeightUnit, t1.objPropJuveniles, t1.objPropLarvae, t1.objPropLength, t1.objPropLengthUnit, t1.objPropMale, t1.objPropObservation, t1.objPropObservationComments, t1.objPropPupae, t1.objPropSex, t1.objPropStadium, t1.objPropWeight, t1.objPropWeightUnit, t1.objPropWidth, t1.objPropWidthUnit, t1.objSiteComments, t1.objStorageComments, t1.objStorageContainerNumber, t1.objStorageContainerPieces, t1.objStorageContainerType, t1.objStorageLevel1, t1.objStorageLevel2, t1.objStorageLevel3, t1.objStorageLevel4, t1.objStorageLevel5, t1.objStorageNumberInContainer, t1.objstoragePieces, t1.objStorageValue, t1.objStorageValueUnit, t1.objAddText1, t1.objAddText10, t1.objAddText2, t1.objAddText3, t1.objAddText4, t1.objAddText5, t1.objAddText6, t1.objAddText7, t1.objAddText8, t1.objAddText9, t1.objIdCollection, t1.objCommonIdReference, t1.objDetIdContact, t1.objDetIdReference, t1.objEventIdContact, t1.objIdExcursion, t1.objOriginIdContact, t1.objPreparationIdContact, t1.objIdProject, t1.objSiteIdSite, t1.objdetIdTaxon
FROM tTaxa t0, tObjects t1
WHERE (
t0.taxIdTaxon IN (
SELECT t2.taxIdTaxon
FROM tTaxa t2
WHERE (t2.taxTaxonDisplay LIKE 'Test Taxon 1'
OR t2.taxSynIdTaxon IN (
SELECT t3.taxSynIdTaxon
FROM tTaxa t3
WHERE t3.taxTaxonDisplay LIKE 'Test Taxon 1'
)
)
) AND (t0.taxIdTaxon = t1.objdetIdTaxon)
)
this seems strange to me, but it is working - and it is faster than my alternative query, which includes a inner join
NOTE: Eclipselink does ignore the JoinType. regardless what you pass it takes an left outer join. (documentation says something else!)
finally i provide the two examples for join and joinless
private static Predicate addSynonymsWithJoins(Root<BioObjectImpl> r, CriteriaBuilder b, CriteriaQuery cq,
Attribute attr, Path path, Object value) {
Join taxJoin = r.join(BioObjectEnum.taxon.name(), JoinType.INNER);
Path<Object> taxValidSynonymId = taxJoin.get(TaxonEnum.validSynonymId.name());
Subquery<TaxonImpl> innerSubquery = cq.subquery(TaxonImpl.class);
Root fromSubTax = innerSubquery.from(TaxonImpl.class);
innerSubquery.select(fromSubTax.<Integer> get(TaxonEnum.id.name()));
Predicate dynamic1 = cb.like(fromSubTax.get(TaxonEnum.name.name()),
NAME_LIKE);
innerSubquery.where(dynamic1);
Predicate dynamic2 = resolveComparator(b, attr, taxJoin.get(attr.getPropertyName()), attr.getValue());//
Predicate p = b.or(taxValidSynonymId.in(innerSubquery), dynamic2);
return p;
}
private static Predicate addSynonymsWithoutJoins(Root<BioObjectImpl> r, CriteriaBuilder b, CriteriaQuery cq,
Attribute attr, Path path, Object value) {
cq.select(r);
Path<Integer> objTaxonId = r.<Integer> get(BioObjectEnum.taxon.name()).get(TaxonEnum.id.name());
Subquery<Integer> t2 = cq.subquery(Integer.class);
Root<TaxonImpl> t2fromTaxon = t2.from(TaxonImpl.class);
Path<Integer> t2taxId = t2fromTaxon.<Integer> get(TaxonEnum.validSynonymId.name());
t2.select(t2taxId);
Predicate t2dynamicWhere = resolveComparator(b, attr, t2fromTaxon.get(attr.getPropertyName()), attr.getValue());
t2.where(t2dynamicWhere);
Subquery<Integer> t1 = cq.subquery(Integer.class);
Root<TaxonImpl> t1fromTaxon = t1.from(TaxonImpl.class);
Predicate t1dynamicWhere = b.like(fromSubTax.get(TaxonEnum.name.name()),
NAME_LIKE);
Path<Integer> t1Select = t1fromTaxon.<Integer> get(TaxonEnum.id.name());
t1.select(t1Select);
Path<Integer> t1TaxSynonymId = t1fromTaxon.<Integer> get(TaxonEnum.validSynonymId.name());
t1dynamicWhere = b.or(t1dynamicWhere, t1TaxSynonymId.in(t2));
t1.where(t1dynamicWhere);
Predicate where = objTaxonId.in(t1);
return where;
}
Related
How to prevent Hibernate to load collection with back reference when I need only count()
The goal is to count collection elements without initializing collection. I made it work in some way, but it's not the soulution that I'd say I want. Back reference is needed because each Price gets some data from Article while being indexed by Hibernate Search. Join column gives me an option to have only two tables, avoiding 3rd linking table. #Entity #Indexed class Article { String name; #JsonManagedReference #OneToMany #LazyCollection(org.hibernate.annotations.LazyCollectionOption.EXTRA) #JoinColumn(name = "article_id") #Field(...bridge = #FieldBridge(impl = PriceBridge.class)) Set<Price> prices; private User created; private User updated; } #Entity #Indexed class Price { #Reference #JsonBackReference #ManyToOne(fetch=FetchType.LAZY) #Field(...bridge = #FieldBridge(impl = PriceArticleBridge.class)) private Article article; #ManyToOne private Provider provider; #ManyToOne private CustomCurrency currency; private BigDecimal amount; private User created; private User updated; } This setup gives me 2 tables where Price table has article_id and there is no 3rd table for linking purposes. But while loading Article and issuing prices.size(), the whole collection is fetched. This is not good because many other entities are loaded too: Provider from Price and User many times because Provider also has its own 2 properties of User to track creator and updater. When there is no #JoinColumn, 3rd linking table is created and then it starts to use COUNT() instead of loading the whole collection. My only question is: How can I keep only 2 tables and use .size() without loading the whole collection? SQL example when not having #JoinColumn: select count(prices_id) from article_prices where article_id =? SQL example when having #JoinColumn (11 tables joined): SELECT prices0_.article_id AS article14_18_0_, prices0_.id AS id1_18_0_, prices0_.id AS id1_18_1_, prices0_.date_created AS date_cre2_18_1_, prices0_.date_last_update AS date_las3_18_1_, prices0_.created_by_id AS created12_18_1_, prices0_.last_update_by_id AS last_up13_18_1_, prices0_.amount AS amount4_18_1_, prices0_.article_id AS article14_18_1_, prices0_.availability AS availabi5_18_1_, prices0_.currency_id AS currenc15_18_1_, prices0_.description AS descript6_18_1_, prices0_.local_date_time_valid_from AS local_da7_18_1_, prices0_.local_date_time_valid_to AS local_da8_18_1_, prices0_.price_url AS price_ur9_18_1_, prices0_.provider_id AS provide16_18_1_, prices0_.purchase_url AS purchas10_18_1_, prices0_.zone_id_valid_from_to AS zone_id11_18_1_, user1_.id AS id1_27_2_, user1_.date_created AS date_cre2_27_2_, user1_.date_last_update AS date_las3_27_2_, user1_.created_by_id AS created13_27_2_, user1_.last_update_by_id AS last_up14_27_2_, user1_.display_name AS display_4_27_2_, user1_.failed_login_attempts AS failed_l5_27_2_, user1_.full_name AS full_nam6_27_2_, user1_.note AS note7_27_2_, user1_.object_status AS object_s8_27_2_, user1_.password AS password9_27_2_, user1_.phone AS phone10_27_2_, user1_.time_zone_id AS time_zo11_27_2_, user1_.username AS usernam12_27_2_, user2_.id AS id1_27_3_, user2_.date_created AS date_cre2_27_3_, user2_.date_last_update AS date_las3_27_3_, user2_.created_by_id AS created13_27_3_, user2_.last_update_by_id AS last_up14_27_3_, user2_.display_name AS display_4_27_3_, user2_.failed_login_attempts AS failed_l5_27_3_, user2_.full_name AS full_nam6_27_3_, user2_.note AS note7_27_3_, user2_.object_status AS object_s8_27_3_, user2_.password AS password9_27_3_, user2_.phone AS phone10_27_3_, user2_.time_zone_id AS time_zo11_27_3_, user2_.username AS usernam12_27_3_, user3_.id AS id1_27_4_, user3_.date_created AS date_cre2_27_4_, user3_.date_last_update AS date_las3_27_4_, user3_.created_by_id AS created13_27_4_, user3_.last_update_by_id AS last_up14_27_4_, user3_.display_name AS display_4_27_4_, user3_.failed_login_attempts AS failed_l5_27_4_, user3_.full_name AS full_nam6_27_4_, user3_.note AS note7_27_4_, user3_.object_status AS object_s8_27_4_, user3_.password AS password9_27_4_, user3_.phone AS phone10_27_4_, user3_.time_zone_id AS time_zo11_27_4_, user3_.username AS usernam12_27_4_, user4_.id AS id1_27_5_, user4_.date_created AS date_cre2_27_5_, user4_.date_last_update AS date_las3_27_5_, user4_.created_by_id AS created13_27_5_, user4_.last_update_by_id AS last_up14_27_5_, user4_.display_name AS display_4_27_5_, user4_.failed_login_attempts AS failed_l5_27_5_, user4_.full_name AS full_nam6_27_5_, user4_.note AS note7_27_5_, user4_.object_status AS object_s8_27_5_, user4_.password AS password9_27_5_, user4_.phone AS phone10_27_5_, user4_.time_zone_id AS time_zo11_27_5_, user4_.username AS usernam12_27_5_, customcurr5_.id AS id1_9_6_, customcurr5_.date_created AS date_cre2_9_6_, customcurr5_.date_last_update AS date_las3_9_6_, customcurr5_.created_by_id AS created10_9_6_, customcurr5_.last_update_by_id AS last_up11_9_6_, customcurr5_.is_default AS is_defau4_9_6_, customcurr5_.is_reference AS is_refer5_9_6_, customcurr5_.java_currency AS java_cur6_9_6_, customcurr5_.object_status AS object_s7_9_6_, customcurr5_.sign_position AS sign_pos8_9_6_, customcurr5_.val AS val9_9_6_, user6_.id AS id1_27_7_, user6_.date_created AS date_cre2_27_7_, user6_.date_last_update AS date_las3_27_7_, user6_.created_by_id AS created13_27_7_, user6_.last_update_by_id AS last_up14_27_7_, user6_.display_name AS display_4_27_7_, user6_.failed_login_attempts AS failed_l5_27_7_, user6_.full_name AS full_nam6_27_7_, user6_.note AS note7_27_7_, user6_.object_status AS object_s8_27_7_, user6_.password AS password9_27_7_, user6_.phone AS phone10_27_7_, user6_.time_zone_id AS time_zo11_27_7_, user6_.username AS usernam12_27_7_, user7_.id AS id1_27_8_, user7_.date_created AS date_cre2_27_8_, user7_.date_last_update AS date_las3_27_8_, user7_.created_by_id AS created13_27_8_, user7_.last_update_by_id AS last_up14_27_8_, user7_.display_name AS display_4_27_8_, user7_.failed_login_attempts AS failed_l5_27_8_, user7_.full_name AS full_nam6_27_8_, user7_.note AS note7_27_8_, user7_.object_status AS object_s8_27_8_, user7_.password AS password9_27_8_, user7_.phone AS phone10_27_8_, user7_.time_zone_id AS time_zo11_27_8_, user7_.username AS usernam12_27_8_, provider8_.id AS id1_20_9_, provider8_.date_created AS date_cre2_20_9_, provider8_.date_last_update AS date_las3_20_9_, provider8_.created_by_id AS created23_20_9_, provider8_.last_update_by_id AS last_up24_20_9_, provider8_.text_id_map AS text_id_4_20_9_, provider8_.address_search_aid AS address_5_20_9_, provider8_.alternate_country_id AS alterna25_20_9_, provider8_.city_id AS city_id26_20_9_, provider8_.lat AS lat6_20_9_, provider8_.lng AS lng7_20_9_, provider8_.street_line1 AS street_l8_20_9_, provider8_.street_line2 AS street_l9_20_9_, provider8_.zip AS zip10_20_9_, provider8_.company_status AS company11_20_9_, provider8_.compassion_level AS compass12_20_9_, provider8_.emails AS emails13_20_9_, provider8_.phones AS phones14_20_9_, provider8_.social_media AS social_15_20_9_, provider8_.urls AS urls16_20_9_, provider8_.description AS descrip17_20_9_, provider8_.importance AS importa18_20_9_, provider8_.name AS name19_20_9_, provider8_.object_status AS object_20_20_9_, provider8_.parent_id AS parent_27_20_9_, provider8_.search_aid AS search_21_20_9_, provider8_.short_name AS short_n22_20_9_, user9_.id AS id1_27_10_, user9_.date_created AS date_cre2_27_10_, user9_.date_last_update AS date_las3_27_10_, user9_.created_by_id AS created13_27_10_, user9_.last_update_by_id AS last_up14_27_10_, user9_.display_name AS display_4_27_10_, user9_.failed_login_attempts AS failed_l5_27_10_, user9_.full_name AS full_nam6_27_10_, user9_.note AS note7_27_10_, user9_.object_status AS object_s8_27_10_, user9_.password AS password9_27_10_, user9_.phone AS phone10_27_10_, user9_.time_zone_id AS time_zo11_27_10_, user9_.username AS usernam12_27_10_, user10_.id AS id1_27_11_, user10_.date_created AS date_cre2_27_11_, user10_.date_last_update AS date_las3_27_11_, user10_.created_by_id AS created13_27_11_, user10_.last_update_by_id AS last_up14_27_11_, user10_.display_name AS display_4_27_11_, user10_.failed_login_attempts AS failed_l5_27_11_, user10_.full_name AS full_nam6_27_11_, user10_.note AS note7_27_11_, user10_.object_status AS object_s8_27_11_, user10_.password AS password9_27_11_, user10_.phone AS phone10_27_11_, user10_.time_zone_id AS time_zo11_27_11_, user10_.username AS usernam12_27_11_ FROM price_info prices0_ LEFT OUTER JOIN veg_user user1_ ON prices0_.created_by_id=user1_.id LEFT OUTER JOIN veg_user user2_ ON user1_.created_by_id=user2_.id LEFT OUTER JOIN veg_user user3_ ON user1_.last_update_by_id=user3_.id LEFT OUTER JOIN veg_user user4_ ON prices0_.last_update_by_id=user4_.id LEFT OUTER JOIN custom_currency customcurr5_ ON prices0_.currency_id=customcurr5_.id LEFT OUTER JOIN veg_user user6_ ON customcurr5_.created_by_id=user6_.id LEFT OUTER JOIN veg_user user7_ ON customcurr5_.last_update_by_id=user7_.id LEFT OUTER JOIN provider provider8_ ON prices0_.provider_id=provider8_.id LEFT OUTER JOIN veg_user user9_ ON provider8_.created_by_id=user9_.id LEFT OUTER JOIN veg_user user10_ ON provider8_.last_update_by_id=user10_.id WHERE prices0_.article_id = ?
Not sure about your objectives, however sometime following trick could help: public class Article { ... Set<Price> prices; #Formula("select count(*) from price where article_id=:id") private int priceCount; public int getPriceCount() { if (Hibernate.isInitialized(prices)) { return prices == null ? 0 : prices.size(); } return priceCount; } }
Performance issue with Criteria API
I am doing a dynamic query using Criteria API, the problem I have is that when this query is executed, each query is repeated for each of the records returned by the query (this is shown by the Hibernate console). Then I get very high response times. My specification class is as follows: public class PacienteSpecification implements Specification<Paciente> { private Paciente filter; public PacienteSpecification(Paciente filter) { super(); this.filter = filter; } public Predicate toPredicate(Root<Paciente> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { Predicate p = cb.conjunction(); p.getExpressions().add(cb.equal(root.get("eliminado"), "N")); if (filter.getNombres() != "") { p.getExpressions().add(cb.like(cb.upper(root.get("nombres")), "%" + filter.getNombres().toUpperCase() + "%")); } if(filter.getApePaterno() != "") { p.getExpressions().add(cb.or(cb.like(cb.upper(root.get("apePaterno")), "%" + filter.getApePaterno().toUpperCase() + "%"))); } if(filter.getApeMaterno() != "") { p.getExpressions().add(cb.or(cb.like(cb.upper(root.get("apeMaterno")), "%" + filter.getApeMaterno().toUpperCase() + "%"))); } if (filter.getFicha() != "") { p.getExpressions().add(cb.equal(cb.upper(root.get("ficha")), filter.getFicha())); } if(filter.getFechaNacimiento() != null){ p.getExpressions().add(cb.equal(root.get("fechaNacimiento"), filter.getFechaNacimiento())); } if(filter.getGenero() != null){ p.getExpressions().add(cb.equal(root.get("genero"), filter.getGenero())); } return p; } } My service that calls the repository is as follows: List<Paciente> listaPacientes = new ArrayList<Paciente>(); Specification<PacienteDoc> pacienteDocEspecificacion = new PacienteDocEspecification(pacBusqueda.getPacienteDocs().get(0)); final List<PacienteDoc> pacDoc = pacienteDocRep.findAll(pacienteDocEspecificacion); and when making the service call the hibernate console shows me a query for each record: Hibernate: select pacientedo0_.id_paciente_doc as id_paciente_doc1_44_, pacientedo0_.eliminado as eliminado2_44_, pacientedo0_.fecha_creacion as fecha_creacion3_44_, pacientedo0_.fecha_ult_modificacion as fecha_ult_modifica4_44_, pacientedo0_.id_usuario_creacion as id_usuario_creacio5_44_, pacientedo0_.id_usuario_ult_mod as id_usuario_ult_mod6_44_, pacientedo0_.num_documento as num_documento7_44_, pacientedo0_.id_paciente as id_paciente8_44_, pacientedo0_.id_tipo_documento as id_tipo_documento9_44_ from dgs_core.paciente_doc pacientedo0_ where 1=1 Hibernate: select paciente0_.id_paciente as id_paciente1_43_0_, paciente0_.ape_materno as ape_materno2_43_0_, paciente0_.ape_paterno as ape_paterno3_43_0_, paciente0_.celular as celular4_43_0_, paciente0_.id_comuna as id_comuna19_43_0_, paciente0_.direccion as direccion5_43_0_, paciente0_.eliminado as eliminado6_43_0_, paciente0_.email as email7_43_0_, paciente0_.id_estado_civil as id_estado_civil20_43_0_, paciente0_.id_etnia as id_etnia21_43_0_, paciente0_.fecha_creacion as fecha_creacion8_43_0_, paciente0_.fecha_defuncion as fecha_defuncion9_43_0_, paciente0_.fecha_nacimiento as fecha_nacimiento10_43_0_, paciente0_.fecha_ult_modificacion as fecha_ult_modific11_43_0_, paciente0_.ficha as ficha12_43_0_, paciente0_.fono as fono13_43_0_, paciente0_.fono_emergencia as fono_emergencia14_43_0_, paciente0_.id_genero as id_genero22_43_0_, paciente0_.id_unidad_creacion as id_unidad_creacio15_43_0_, paciente0_.id_usuario_creacion as id_usuario_creaci16_43_0_, paciente0_.id_usuario_ult_mod as id_usuario_ult_mo17_43_0_, paciente0_.id_nacionalidad as id_nacionalidad23_43_0_, paciente0_.nombres as nombres18_43_0_, paciente0_.id_prevision as id_prevision24_43_0_, paciente0_.id_profesion as id_profesion25_43_0_, catalogo1_.id_catalogo as id_catalogo1_35_1_, catalogo1_.activo as activo2_35_1_, catalogo1_.comentario as comentario3_35_1_, catalogo1_.id_def_catalogo as id_def_catalogo14_35_1_, catalogo1_.orden as orden4_35_1_, catalogo1_.valido_desde as valido_desde5_35_1_, catalogo1_.valido_hasta as valido_hasta6_35_1_, catalogo1_.valor1 as valor7_35_1_, catalogo1_.valor2 as valor8_35_1_, catalogo1_.valor3 as valor9_35_1_, catalogo1_.valor4 as valor10_35_1_, catalogo1_.valor5 as valor11_35_1_, catalogo1_.valor6 as valor12_35_1_, catalogo1_.version as version13_35_1_, definicion2_.id_def_catalogo as id_def_catalogo1_36_2_, definicion2_.activo as activo2_36_2_, definicion2_.columna1 as columna3_36_2_, definicion2_.columna2 as columna4_36_2_, definicion2_.columna3 as columna5_36_2_, definicion2_.columna4 as columna6_36_2_, definicion2_.columna5 as columna7_36_2_, definicion2_.columna6 as columna8_36_2_, definicion2_.comentario as comentario9_36_2_, definicion2_.nombre_catalogo as nombre_catalogo10_36_2_, definicion2_.valido_desde as valido_desde11_36_2_, definicion2_.valido_hasta as valido_hasta12_36_2_, definicion2_.version as version13_36_2_, catalogo3_.id_catalogo as id_catalogo1_35_3_, catalogo3_.activo as activo2_35_3_, catalogo3_.comentario as comentario3_35_3_, catalogo3_.id_def_catalogo as id_def_catalogo14_35_3_, catalogo3_.orden as orden4_35_3_, catalogo3_.valido_desde as valido_desde5_35_3_, catalogo3_.valido_hasta as valido_hasta6_35_3_, catalogo3_.valor1 as valor7_35_3_, catalogo3_.valor2 as valor8_35_3_, catalogo3_.valor3 as valor9_35_3_, catalogo3_.valor4 as valor10_35_3_, catalogo3_.valor5 as valor11_35_3_, catalogo3_.valor6 as valor12_35_3_, catalogo3_.version as version13_35_3_, catalogo4_.id_catalogo as id_catalogo1_35_4_, catalogo4_.activo as activo2_35_4_, catalogo4_.comentario as comentario3_35_4_, catalogo4_.id_def_catalogo as id_def_catalogo14_35_4_, catalogo4_.orden as orden4_35_4_, catalogo4_.valido_desde as valido_desde5_35_4_, catalogo4_.valido_hasta as valido_hasta6_35_4_, catalogo4_.valor1 as valor7_35_4_, catalogo4_.valor2 as valor8_35_4_, catalogo4_.valor3 as valor9_35_4_, catalogo4_.valor4 as valor10_35_4_, catalogo4_.valor5 as valor11_35_4_, catalogo4_.valor6 as valor12_35_4_, catalogo4_.version as version13_35_4_, catalogo5_.id_catalogo as id_catalogo1_35_5_, catalogo5_.activo as activo2_35_5_, catalogo5_.comentario as comentario3_35_5_, catalogo5_.id_def_catalogo as id_def_catalogo14_35_5_, catalogo5_.orden as orden4_35_5_, catalogo5_.valido_desde as valido_desde5_35_5_, catalogo5_.valido_hasta as valido_hasta6_35_5_, catalogo5_.valor1 as valor7_35_5_, catalogo5_.valor2 as valor8_35_5_, catalogo5_.valor3 as valor9_35_5_, catalogo5_.valor4 as valor10_35_5_, catalogo5_.valor5 as valor11_35_5_, catalogo5_.valor6 as valor12_35_5_, catalogo5_.version as version13_35_5_, catalogo6_.id_catalogo as id_catalogo1_35_6_, catalogo6_.activo as activo2_35_6_, catalogo6_.comentario as comentario3_35_6_, catalogo6_.id_def_catalogo as id_def_catalogo14_35_6_, catalogo6_.orden as orden4_35_6_, catalogo6_.valido_desde as valido_desde5_35_6_, catalogo6_.valido_hasta as valido_hasta6_35_6_, catalogo6_.valor1 as valor7_35_6_, catalogo6_.valor2 as valor8_35_6_, catalogo6_.valor3 as valor9_35_6_, catalogo6_.valor4 as valor10_35_6_, catalogo6_.valor5 as valor11_35_6_, catalogo6_.valor6 as valor12_35_6_, catalogo6_.version as version13_35_6_, catalogo7_.id_catalogo as id_catalogo1_35_7_, catalogo7_.activo as activo2_35_7_, catalogo7_.comentario as comentario3_35_7_, catalogo7_.id_def_catalogo as id_def_catalogo14_35_7_, catalogo7_.orden as orden4_35_7_, catalogo7_.valido_desde as valido_desde5_35_7_, catalogo7_.valido_hasta as valido_hasta6_35_7_, catalogo7_.valor1 as valor7_35_7_, catalogo7_.valor2 as valor8_35_7_, catalogo7_.valor3 as valor9_35_7_, catalogo7_.valor4 as valor10_35_7_, catalogo7_.valor5 as valor11_35_7_, catalogo7_.valor6 as valor12_35_7_, catalogo7_.version as version13_35_7_, catalogo8_.id_catalogo as id_catalogo1_35_8_, catalogo8_.activo as activo2_35_8_, catalogo8_.comentario as comentario3_35_8_, catalogo8_.id_def_catalogo as id_def_catalogo14_35_8_, catalogo8_.orden as orden4_35_8_, catalogo8_.valido_desde as valido_desde5_35_8_, catalogo8_.valido_hasta as valido_hasta6_35_8_, catalogo8_.valor1 as valor7_35_8_, catalogo8_.valor2 as valor8_35_8_, catalogo8_.valor3 as valor9_35_8_, catalogo8_.valor4 as valor10_35_8_, catalogo8_.valor5 as valor11_35_8_, catalogo8_.valor6 as valor12_35_8_, catalogo8_.version as version13_35_8_ from dgs_core.paciente paciente0_ left outer join dgs_core.catalogo catalogo1_ on paciente0_.id_comuna=catalogo1_.id_catalogo left outer join dgs_core.definicion_catalogo definicion2_ on catalogo1_.id_def_catalogo=definicion2_.id_def_catalogo left outer join dgs_core.catalogo catalogo3_ on paciente0_.id_estado_civil=catalogo3_.id_catalogo left outer join dgs_core.catalogo catalogo4_ on paciente0_.id_etnia=catalogo4_.id_catalogo left outer join dgs_core.catalogo catalogo5_ on paciente0_.id_genero=catalogo5_.id_catalogo left outer join dgs_core.catalogo catalogo6_ on paciente0_.id_nacionalidad=catalogo6_.id_catalogo left outer join dgs_core.catalogo catalogo7_ on paciente0_.id_prevision=catalogo7_.id_catalogo left outer join dgs_core.catalogo catalogo8_ on paciente0_.id_profesion=catalogo8_.id_catalogo where paciente0_.id_paciente=?
It seems that Your entity mapping is more or less sth like this: public class Paciente { ... #OneToMany(fetch=FetchType.EAGER) private Set<PacienteDoc> docs = new HashSet<>(); ... } And then You run into What is the "N+1 selects problem" in ORM (Object-Relational Mapping)? To fix that simply change #OneToMany(fetch=FetchType.EAGER) to #OneToMany which is equal to #OneToMany(fetch=FetchType.LAZY)
Passing a parameter in a jpql query select
I have a jpql query instanciates a java object in select clause public List<ChampEtatOT> getEtatOT(Date dateDebut, Date dateFin) { Query query = em.createQuery("SELECT NEW ChampEtatOT( ot.numero, uo.denominationFr, ot.etat, ot.dateDebutReelle , ot.dateFinReelle, :dateParam1, :dateParam2, :dateParam3) FROM ordre ot JOIN ot.unite uo") .setParameter("dateParam1", dateDebut, TemporalType.DATE) .setParameter("dateParam2", dateFin, TemporalType.DATE) .setParameter("dateParam3", new Date("2015-01-01"), TemporalType.DATE); return query.getResultList(); } I put 3 parameters, so i can pass it in the constructor I get this error Caused by: Exception [EclipseLink-6137] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.QueryExceptionException Description: An Exception was thrown while executing a ReportQuery with a constructor expression: java.lang.NoSuchMethodException: dz.elit.gmao.commun.reporting.classe.ChampEtatOT.<init>(java.lang.String, java.lang.String, java.lang.String, java.util.Date, java.util.Date)Query: ReportQuery(referenceClass=TravOrdreTravail jpql="SELECT NEW dz.elit.gmao.commun.reporting.classe.ChampEtatOT( ot.numero, uo.denominationFr, ot.etat, ot.dateDebutReelle , ot.dateFinReelle, :dateParam1, :dateParam2, :dateParam3) FROM TravOrdreTravail ot JOIN ot.uniteOrganisationnellle uo") I think that it's not possible to put parameters in a select clause so does anyone have an idea, the constructor method is as follows: public ChampEtatOT(String numero, String denominationFr, String etat, Date dateDebutReelle, Date dateFinReelle, Date dateParam1, Date dateParam2, Date dateParam3) { this.numero = numero; this.denominationFr = denominationFr; if (etat.equals("OUV")) { if (dateDebutReelle.before(dateParam1)) { etatEntreeSortie = "En instance debut du mois"; } else { if (dateDebutReelle.before(dateParam2)) { etatEntreeSortie = "En instance fin du mois"; } else { if (dateDebutReelle.after(dateParam1) && dateDebutReelle.before(dateParam2)) { etatEntreeSortie = "Entree/Mois"; } } } } }
Problem solved, as you suggested bRIMOs Bor it's not possible to pass parameters in a SELECT clause, so i have retreived all the results in a List than filtered the results according to the three dates date1, date2, date3 Query query = em.createQuery("SELECT NEW ChampEtatAteliers" + "( ot.numero, uo.denominationFr, ot.etat, ot.dateDebutReelle, ot.dateFinReelle) " + "FROM ordre ot JOIN ot.unite uo"); List<ChampEtatAteliers> champEtatAtelierses = query.getResultList(); for (ChampEtatAteliers champEtatAtelierse : champEtatAtelierses) { if (champEtatAtelierse.getDateDebutReelle().compareTo(date1) >= 0 && champEtatAtelierse.getDateDebutReelle().compareTo(date2) <= 0) { champEtatAtelierList2.add(new ChampEtatAteliers(champEtatAtelierse.getNumero(), champEtatAtelierse.getDenominationFr(), "Entree/Mois")); } if (champEtatAtelierse.getEtat().equals("OUV")) { if (champEtatAtelierse.getDateDebutReelle().compareTo(date1) < 0) { champEtatAtelierse.setEtatEntreeSortie("En instance début du mois"); } else { if (champEtatAtelierse.getDateDebutReelle().compareTo(date2) <= 0) { champEtatAtelierse.setEtatEntreeSortie("En instance fin du mois"); } } } }
I think that it's not possible to reference a parameter in the contructor. in your case it throws a NoSuchMethodexeption : it means that, no method with the current signature in your ChampEtatOT class (5 parameters instead of 8 ) you can refer to this answer => Passing a parameter in a jpql query select So ,try to retrive all data then make a filter method to set all the etatEntreeSortie values inside the ChampEtatOT class of the ResultList
Clearly the JPQL BNF does permit passing parameters as constructor arguments. constructor_expression ::= NEW constructor_name ( constructor_item {, constructor_item}* ) constructor_item ::= single_valued_path_expression | scalar_expression | aggregate_expression | identification_variable scalar_expression ::= simple_arithmetic_expression | string_primary | enum_primary | datetime_primary | boolean_primary | case_expression | entity_type_expression string_primary ::= state_field_path_expression | string_literal | input_parameter | functions_returning_strings | aggregate_expression | case_expression i.e a scalar_expression can be a string_primary, which can be an input_parameter. So your JPA provider is not meeting the JPA spec and you should raise a bug on it.
[Hive]I got "ArrayIndexOutOfBoundsException" while I query the hive database
I always get "ArrayIndexOutOfBoundsException" while I query the hive base(both hive-0.11.0 and hive-0.12.0), but sometimes not. Here is the error java.lang.RuntimeException: Hive Runtime Error while closing operators: java.lang.ArrayIndexOutOfBoundsException: 0 at org.apache.hadoop.hive.ql.exec.mr.ExecReducer.close(ExecReducer.java:313) at org.apache.hadoop.io.IOUtils.cleanup(IOUtils.java:232) at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:539) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:421) at org.apache.hadoop.mapred.Child$4.run(Child.java:255) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190) at org.apache.hadoop.mapred.Child.main(Child.java:249) Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.ArrayIndexOutOfBoundsException: 0 at org.apache.hadoop.hive.ql.exec.persistence.RowContainer.first(RowContainer.java:231) at org.apache.hadoop.hive.ql.exec.persistence.RowContainer.first(RowContainer.java:74) at org.apache.hadoop.hive.ql.exec.CommonJoinOperator.genUniqueJoinObject(CommonJoinOperator.java:645) at org.apache.hadoop.hive.ql.exec.CommonJoinOperator.checkAndGenObject(CommonJoinOperator.java:758) at org.apache.hadoop.hive.ql.exec.JoinOperator.endGroup(JoinOperator.java:257) at org.apache.hadoop.hive.ql.exec.mr.ExecReducer.close(ExecReducer.java:298) ... 8 more Caused by: java.lang.ArrayIndexOutOfBoundsException: 0 at org.apache.hadoop.hive.ql.exec.persistence.RowContainer.first(RowContainer.java:220) ... 13 more Could someone help me? Update my code: Select distinct jabberUseragent.gameID,agentPlayInfo.gameLabel,jabberUseragent.userAgent,CONCAT(CONCAT(CONCAT(triggerUsageStart.generateDate,' '),triggerUsageStart.timezone),CONCAT(' ',triggerUsageStart.generateTime)) as generateDate,(unix_timestamp(CONCAT(CONCAT(triggerUsageStop.generateDate,' '),triggerUsageStop.generateTime)) - unix_timestamp(CONCAT(CONCAT(triggerUsageStart.generateDate,' '),triggerUsageStart.generateTime))) from (Select gameSession,gameID,userAgent from(Select distinct regexp_extract(t.payload,'playRequestId:(.*), playRequest',1) as gameSession,regexp_extract(t.payload,'gameId:(.*), userAgent:',1) as gameID,regexp_extract(t.payload,', userAgent:(.*), agentLocation',1) as userAgent,payload from (select * from ${hiveconf:DATA_BASE} p where p.dt >= '${hiveconf:LOW_DATE}' and p.dt <= '${hiveconf:UPPER_DATE}') t where CONCAT(t.generatedate,t.generatetime) >= CONCAT('${hiveconf:LOW_DATE}','${hiveconf:LOW_TIME}') and CONCAT(t.generatedate,t.generatetime) <= CONCAT('${hiveconf:UPPER_DATE}','${hiveconf:UPPER_TIME}'))jabberUseragent where jabberUseragent.gameSession!='' and jabberUseragent.userAgent!='') jabberUseragent join (Select gameID,gameLabel from(Select distinct regexp_extract(t.payload,'gameId=(.*),gameLabel=.*,configFilePath',1) as gameID,regexp_extract(t.payload,'gameId=.*,gameLabel=(.*),configFilePath',1) as gameLabel,payload from (select * from ${hiveconf:DATA_BASE} p where p.dt >= '${hiveconf:LOW_DATE}' and p.dt <= '${hiveconf:UPPER_DATE}') t where CONCAT(t.generatedate,t.generatetime) >= CONCAT('${hiveconf:LOW_DATE}','${hiveconf:LOW_TIME}') and CONCAT(t.generatedate,t.generatetime) <= CONCAT('${hiveconf:UPPER_DATE}','${hiveconf:UPPER_TIME}'))agentPlayInfo where agentPlayInfo.gameID!='' and agentPlayInfo.gameLabel!='') agentPlayInfo join (Select gameSession,generateDate,generateTime,timezone,payload from(Select distinct regexp_extract(t.payload,'GAME_SESSION=.*((.{8})-(.{4})-(.{4})-(.{4})-(.{12}))\" USAGE=\"([\\w\\-\\(\\)\\.]*,){41}9.*\"',1) as gameSession,generateDate,generateTime,timezone,payload from (select * from ${hiveconf:DATA_BASE} p where p.dt >= '${hiveconf:LOW_DATE}' and p.dt <= '${hiveconf:UPPER_DATE}') t where t.payload like '%[e] usage_record%' and CONCAT(t.generatedate,t.generatetime) <= CONCAT('${hiveconf:UPPER_DATE}','${hiveconf:UPPER_TIME}') and CONCAT(t.generatedate,t.generatetime) >= CONCAT('${hiveconf:LOW_DATE}','${hiveconf:LOW_TIME}'))triggerStart where triggerStart.gameSession!='')triggerUsageStart join (Select gameSession,generateDate,generateTime,timezone,payload from(Select distinct regexp_extract(t.payload,'GAME_SESSION=.*((.{8})-(.{4})-(.{4})-(.{4})-(.{12}))\" USAGE=\"([\\w\\-\\(\\)\\.]*,){41}[1-5].*\"',1) as gameSession,generateDate,generateTime,timezone,payload from (select * from ${hiveconf:DATA_BASE} p where p.dt >= '${hiveconf:LOW_DATE}' and p.dt <= '${hiveconf:UPPER_DATE}') t where t.payload like '%[e] usage_record%' and CONCAT(t.generatedate,t.generatetime) <= CONCAT('${hiveconf:UPPER_DATE}','${hiveconf:UPPER_TIME}') and CONCAT(t.generatedate,t.generatetime) >= CONCAT('${hiveconf:LOW_DATE}','${hiveconf:LOW_TIME}'))triggerStop where triggerStop.gameSession!='')triggerUsageStop on (jabberUseragent.gameSession = triggerUsageStart.gameSession and triggerUsageStart.gameSession = triggerUsageStop.gameSession and jabberUseragent.gameID = agentPlayInfo.gameID) order by generateDate Sorry, I can't share my samples. By the way, I've also got this exception before I got "ArrayIndexOutOfBoundException" javax.jdo.JDODataStoreException: Error executing SQL query "select PARTITIONS.PART_ID from PARTITIONS inner join TBLS on PARTITIONS.TBL_ID = TBLS.TBL_ID inner join DBS on TBLS.DB_ID = DBS.DB_ID where TBLS.TBL_NAME = ? and DBS.NAME = ? and PARTITIONS.PART_NAME in (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)". at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:451) at org.datanucleus.api.jdo.JDOQuery.executeWithArray(JDOQuery.java:321) at org.apache.hadoop.hive.metastore.MetaStoreDirectSql.getPartitionsViaSqlFilterInternal(MetaStoreDirectSql.java:181) at org.apache.hadoop.hive.metastore.MetaStoreDirectSql.getPartitionsViaSqlFilter(MetaStoreDirectSql.java:82) at org.apache.hadoop.hive.metastore.ObjectStore.getPartitionsByNamesInternal(ObjectStore.java:1717) at org.apache.hadoop.hive.metastore.ObjectStore.getPartitionsByNames(ObjectStore.java:1700) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)...... NestedThrowablesStackTrace: org.postgresql.util.PSQLException: ERROR: relation "partitions" does not exist at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:1591) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1340) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:192) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:471) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:373) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:258)......
Based on the information provided, only this can be a sensible solution to your problem. I have put the method definition for reference. Please go through it to understand If you run down the source code closely, there are two areas / possibilities where ArrayIndexOutOfBoundException can be thrown. Accessing the array values of input splits from Configuration Reading the Row from currentReadBlock array (this is mostly not the case for the exception since it's size is greater than 0) Please check your set of input files for job because InputFormat#split() method returns an array of InputSplit type. Each InputSplit is then assigned to an individual Mapper for processing. Mostly, the exception occurs while accessing this InputSplit[] array.
hibernate restrictions.in with and, how to use?
I have table like below id, employee_no, survey_no, name 1 test 1 test_name 2 test2 1 test_name2 3 test3 1 test_name3 4 test4 2 test_name4 how to query with Restriction.in by combining below AND into one IN statement? IN[ (if(survey_no==1) && employee_no== 'test') , (if(survey_no==1) && employee_no== 'test2') , ... ]
I think this is the criteria combination you want to use (btw. it is easier to help with the Hibernate entity bean definition instead of the table structure): String[] employeeNames = { "test", "test2" }; List<Survey> surveys = getSession().createCriteria(Survey.class).add( Restrictions.and ( Restrictions.eq("surveyNumber", 1), Restrictions.in("employeeName", employeeNames) ) ).list();
List<EmployeeSurvey> employeeSurvey = getSession().createCriteria (EmployeeSurvey.class).add( Restrictions.and ( Restrictions.eq("survey_no", 1), Restrictions.in("employee_name", new String[] {"test", "test1"}) )).list();