JPQL Constructor Expressions, how to eagerly fetch the main entity in 'select new' - sql

The original query I have is somewhat complex, but what I'm trying to do is obtain the entity AlertCondition plus some additional fields.
+ " SELECT new org.rhq.core.domain.alert.composite.AlertConditionEventCategoryComposite " //
+ " ( " //
+ " ac, " //
+ " res.id " //
+ " ) " //
+ " FROM AlertCondition AS ac FETCH ALL PROPERTIES " //
+ " JOIN ac.alertDefinition ad " //
+ " JOIN ad.resource res " //
+ " WHERE " + AlertCondition.RECOVERY_CONDITIONAL_EXPRESSION //
+ " AND ( res.agent.id = :agentId OR :agentId IS NULL ) " //
+ " AND ad.enabled = TRUE " //
+ " AND ad.deleted = FALSE " //
+ " AND ac.category = 'EVENT' " //
+ "ORDER BY ac.id"), //
The problem is Hibernate only selects the ID of AlertCondition, so when accessing this object, this ends up requiring N+1 selects whereas I would like to do only 1.
The select is only fetching the ID column, according to debug:
select alertcondi0_.ID as col_0_0_, alertdefin1_.ID as col_1_0_, resource2_.ID as col_2_0_
What I'm trying to get back are all the fields of *AlertCondition.
I can't find any way to do this under Hibernate. JOIN FETCH doesn't really work here either.
The alternative is to select every column of the table, which I'd like to avoid.

Facing the same issue.
I don't know how to let hibernate fetch ac.* neither.
But I found a workaround.
#Query("select ac, xxx, zzz")
List<Object[]> fetchRecords()
//
Constructor<?> constructor = AlertConditionEventCategoryComposite.class.getDeclaredConstructors()[0];
List<AlertConditionEventCategoryComposite> composites = fetchRecords.stream().map(constructor::newInstance).collect(Collectors.toList());

You can tell hibernate to fetch an ad with:
JOIN FETCH ac.alertDefinition ad

Related

Joining unrelated tables via JPQL

I have the following query which works. All the tables in this query have relations in some way.
#Repository(value = "ARepository")
public interface ARepository extends JpaRepository<CardEntity, String> {
#Query("SELECT xref.shortUtlTx FROM CardEntity card " +
"JOIN card.apexUrlCrossRef xref " +
"JOIN xref.sampleProdOffer offer " +
"WHERE xref.apexCard.cardNumber = :cardNum " +
"AND offer.apexeeOfferId = :myCode"
)
List<String> getAllValues(#Param("cardNum") String cardNum, #Param("myCode") String myCode);
}
But I also wish to join another table (Entity name -> UrlCountEntity) to this query but that table has no relation to the other tables in this query. Is there a way I could do this?
Based on reading a blog, I tried the following but throws errors.
Added this line to the query:
AND EXISTS (SELECT referCount FROM UrlCountEntity referCount WHERE
referCount.url.urlTx = xref.shortUtlTx)
#Repository(value = "ARepository")
public interface ARepository extends JpaRepository<CardEntity, String> {
#Query("SELECT xref.shortUtlTx FROM CardEntity card " +
"JOIN card.apexUrlCrossRef xref " +
"JOIN xref.sampleProdOffer offer " +
"WHERE xref.apexCard.cardNumber = :cardNum " +
"AND offer.apexeeOfferId = :myCode " +
"AND EXISTS (SELECT referCount FROM UrlCountEntity referCount WHERE referCount.url.urlTx = xref.shortUtlTx)"
)
List<String> getAllValues(#Param("cardNum") String cardNum, #Param("myCode") String myCode);
}
Error as follows:
Method threw
'org.springframework.dao.InvalidDataAccessResourceUsageException'
exception.
could not extract ResultSet; SQL [n/a]
Based on this article:
Using Hibernate 5.1 or newer you can join two unrelated tables via JQPL same way you would do it in SQL:
SELECT first
FROM First first JOIN
Second second ON first.property = second.property
WHERE first.property = :param
So you would need to change your query to something like this:
#Query("SELECT xref.shortUtlTx FROM CardEntity card " +
"JOIN card.apexUrlCrossRef xref " +
"JOIN xref.sampleProdOffer offer " +
"JOIN UrlCountEntity referCount ON referCount.url.urlTx = xref.shortUtlTx" +
"WHERE xref.apexCard.cardNumber = :cardNum " +
"AND offer.apexeeOfferId = :myCode")
List<String> getAllValues(#Param("cardNum") String cardNum, #Param("myCode") String myCode);

Running HQL query in console

I am trying to run the following query in IntelliJ:
#Query(value = "" +
"SELECT offer FROM OfferEntity offer " +
" JOIN offer.placeOwnership AS owner " +
" JOIN owner.place AS place " +
"WHERE " +
" place.id = :placeId AND " +
" offer.dayFrom = :offerDate AND " +
" offer.repeating = false")
as I am doing so, I get ask to provide the parameters placeId and offerDate. My problem is I have no idea about the latter.
I have no idea how I can run this query.
I also tried to run it manually inside the console like this:
SELECT offer FROM OfferEntity offer
JOIN offer.placeOwnership AS owner
JOIN owner.place AS place
WHERE
place.id = 1L AND
offer.dayFrom = java.time.LocalDate.parse("2018-10-08") AND
offer.repeating = false
but that gives my a syntax error.

#query with named #param returning empty result set when using sql IN

Btw this is already working with a jdbc template based solution that I wrote. It's not me wanting to do the rewrite, it is the tec lead's idea. It is giving me a headache.
Lets not get into the discussion on why this is or isn't a good idea, but rather how to make it work.
in my repo
#Repository
interface Foo...extends JpaRepository
this works:
#Query(value = "SELECT t.td, em.ct, j.dsc AS bs, ct.dsc AS ct_name, "
+ "t.tn, et.dsc, f.f_id, f.f_life, f.fl_name, em.f_note "
+ "FROM ext_master em join tax t on em.td = t.td "
+ "join bs j on j.bs = t.bs "
+ "join ex_type et on em.ex_type = et.ex_type "
+ "join ct ct on ct.ct = em.ct "
+ "left join ex_f ef on em.td = ef.td and em.ct = ef.ct "
+ "left join f f on ef.f_id = f.f_id "
+ "WHERE em.ct in ( 'CC' ) "
+ "AND t.state IN ('FF','AK','AL','GA')"
+ "ORDER BY bs, t.tn", nativeQuery = true)
List<Object> getExtensionsByCustTypeAndState(#Param("custTypes") String custTypes, #Param("states") String states);
this doesn't returns empty result set
#Query(value = "SELECT t.td, em.ct, j.dsc AS bs, ct.dsc AS ct_name, "
+ "t.tn, et.dsc, f.f_id, f.f_life, f.fl_name, em.f_note "
+ "FROM extension_master em join tax t on em.td = t.td "
+ "join bs j on j.bs = t.bs "
+ "join exemption_type et on em.ex_type = et.ex_type "
+ "join ct ct on ct.ct = em.ct "
+ "left join ex_f ef on em.td = ef.td and em.ct = ef.ct "
+ "left join f f on ef.f_id = f.f_id "
+ "WHERE em.ct in ( :custTypes ) "
+ "AND t.state IN ('FF', :states)"
+ "ORDER BY bs, t.tn", nativeQuery = true)
List<Object> getExByCustTypeAndState(#Param("custTypes") String custTypes, #Param("states") String states);
both can have one or multiple values, I tried:
with both params like {:states} :#{#states}
with the value inside the param
surrounded by " or by '
passing the whole line in the parameter like "AND t.state IN ('FF','AK','AL','GA')"
passing the 'FF','AK','AL','GA' in the states param and subtituting the in the query with
+ "AND t.state IN ( :states)"
I did write a simple query to make sure I am getting the parameters passed in right. so that's working.
Can anyone write this right, so that the in statements work, or tell me why it is not possible.
Thank you.
You pass all the possible values in one parameter that's why you don't get the results you are expecting.
You have to change the where clause like this:
"WHERE em.ct in ( :custTypes1, :custTypes2, :custTypes3 .... :custTypesN) "
this ended up being the simplest solution
instead of :
"WHERE em.ct in ( :custTypes ) "
+ "AND t.state IN ('FF', :states)"
do:
"WHERE em.ct in :custTypes "
+ "AND t.state IN :states "
and add the FF to the states string on before I call the function.

native query with spring data jpa doesn't return result

Hello I have written the following method in spring data jpa repo:
#RestResource(exported = false)
#Query(
value = "select q.* " +
"from question q " +
"left join question_program qp " +
"on q.question_id = qp.question_id " +
"where " +
"q.difficulty_level_id = ?1 " +
"and " +
"q.paid = false " +
"and " +
"qp.program_id = ?2 " +
"order by random() " +
"limit ?3",
nativeQuery = true
)
List<Question> getFreeRandomQuestions(
#Param("df") Integer df,
#Param("programId") Integer programId,
#Param("qs") Integer qs);
It is returning an empty list whereas when I run the same query in pgadmin I get all the desired rows. It also works in spring data jpa if I remove the join with question_program. What am I doing wrong?
UPDATE:
I have tried select q ... and select * .... Both have the same problem
UPDATE:
I kind of solved this by implementing a service which fetches that data using sessionFactory and raw sql query!.

"where" restrictions not working on hql query with join clause

First of all clarify that I am quite bad with databases, so please do not be to mean with my code :P
I have a problem with a query on hibernate using join and restrictions. I have a huge list of Assignments and some of them have an Asr object.
queryString.append("select new commons.bo.assignment.AssignmentAssociateExtract("
+ " assignment.id, assignment.contract.assignmentStatus,"
+ " assignment.contract.beginDate, assignment.contract.endDate,"
+ " assignment.contract.contractType, assignment.organizationalData.homeCountryKey,"
+ " assignment.organizationalData.hostCountryKey,"
+ " assignment.organizationalData.homeOrgUnitKey,"
+ " assignment.associate.globalIdAssociate,"
+ " assignment.associate.localIdHome,"
+ " assignment.associate.firstName,"
+ " assignment.associate.lastName)"
+ " from Assignment assignment left join assignment.asr asr"
+ " where assignment.contract.assignmentStatus.code = 5"
+ " and asr.homeAsrElegibility is not 'X'"
+ " or asr.homeAsrElegibility is null"
);
I was creating this query step by step. Before I created it without the join clause left join assignment.asr asr and it was working well but of course it was not showing the Assignments that did not have a Asr object. After I added the join clause, now it shows every single Assignment (10.000 records when those who have an assignmentStatus = 5 are just 4.000) and the restrictions like
where assignment.contract.assignmentStatus.code = 5
are not reflected in the result anymore.
So to sum up: I need a list with all assignments with assignmentStatus = 5 and asr.homeAsrElegibility != 'X'. But it needs to include also all assignments with assignmentStatus = 5 even if they do not have an Asr object.
Any ideas?? Thanks!
Parenthesis helps to clarify the situation.
queryString.append("select new commons.bo.assignment.AssignmentAssociateExtract("
+ " assignment.id, assignment.contract.assignmentStatus,"
+ " assignment.contract.beginDate, assignment.contract.endDate,"
+ " assignment.contract.contractType, assignment.organizationalData.homeCountryKey,"
+ " assignment.organizationalData.hostCountryKey,"
+ " assignment.organizationalData.homeOrgUnitKey,"
+ " assignment.associate.globalIdAssociate,"
+ " assignment.associate.localIdHome,"
+ " assignment.associate.firstName,"
+ " assignment.associate.lastName)"
+ " from Assignment assignment left join assignment.asr asr"
+ " where assignment.contract.assignmentStatus.code = 5"
+ " and ((asr.homeAsrElegibility is not null and asr.homeAsrElegibility is not 'X')"
+ " or (asr.homeAsrElegibility is null))"
);