I am not able to understand why the hibernate is not finding the parameter "setor" of the query below.
hql.append("select top :limite * from MA3OCORT oco,MA4DETOT ocodA " +
" where MA4IDOCO=ma3idoco " +
" and ocodA.MA4IDODE in (select max(ocodB.MA4IDODE) from MA4DETOT ocodB where ocodA.MA4IDOCO=ocodB.MA4IDOCO and ocodB.MA4IDSIT=:situacao)" +
" and (oco.MA3DSSOL like :solicitante or :solicitante is null)" +
" and (ocodA.MA4DTDET between :datai and :dataf or :dataf is null)" +
" and ocodA.MA4IDSET = :setor" +
"order by ocodA.MA4DTDET desc");
return em.createNativeQuery(hql.toString(), OcorrenciaDetalhe.class)
.setParameter("situacao", situacao)
.setParameter("solicitante", "%" + solicitanteFiltro + "%")
.setParameter("datai", dataRespostaFiltro1)
.setParameter("dataf", dataRespostaFiltro2)
.setParameter("setor", usuarioLogado.getSetor().getId())
.setParameter("limite", limit).getResultList();
Because there is a syntax error in the select
this
" and ocodA.MA4IDSET = :setor" +
"order by ocodA.MA4DTDET desc");
becomes
' and ocodA.MA4IDSET = :setororder by ocodA.MA4DTDET desc'
You need to add a blank character after :setor or before order.
You have to make a space between sector and order by:
like that :
hql.append("select top :limite * from MA3OCORT oco,MA4DETOT ocodA " +
" where MA4IDOCO=ma3idoco " +
" and ocodA.MA4IDODE in (select max(ocodB.MA4IDODE) from MA4DETOT ocodB where ocodA.MA4IDOCO=ocodB.MA4IDOCO and ocodB.MA4IDSIT=:situacao)" +
" and (oco.MA3DSSOL like :solicitante or :solicitante is null)" +
" and (ocodA.MA4DTDET between :datai and :dataf or :dataf is null)" +
" and ocodA.MA4IDSET = :setor" +
" order by ocodA.MA4DTDET desc");
return em.createNativeQuery(hql.toString(), OcorrenciaDetalhe.class)
.setParameter("situacao", situacao)
.setParameter("solicitante", "%" + solicitanteFiltro + "%")
.setParameter("datai", dataRespostaFiltro1)
.setParameter("dataf", dataRespostaFiltro2)
.setParameter("setor", usuarioLogado.getSetor().getId())
.setParameter("limite", limit).getResultList();
Related
I have a SpringBoot application where I use Repository class to query my Oracle DB table.
Here is how the query and associated function are defined :
#Query( value =" SELECT status "+
" FROM tb1 " +
" WHERE " +
" to_date(cob_Date,'dd-MON-yy') = to_date(:cobDate,'yyyy-mm-dd') " +
" AND business_Day ='BD3' " +
" AND intra_day ='INTRA_06' " +
" AND datasource_name =:datasource" +
" AND upper(status) = 'COMPLETED' " +
" AND frequency = 'MONTHLY' " +
" AND processed = 'Y' " +
" ORDER BY create_date desc FETCH FIRST 1 rows only"
, nativeQuery=true)
List<String> getImpalaJobStatus(#Param("intraDay") String intraDay,
#Param("businessDay") String businessDay,
#Param("cobDate") LocalDate cobDate,
#Param("datasource") String datasource);
If I run this query in SQL developer then I am getting my results back, however if I run it from my SpringBoot Application it returns nothing.
I suspect I am doing something wrong with the Date field "COB_DATE" and this clause under WHERE:
" to_date(cob_Date,'dd-MON-yy') = to_date(:cobDate,'yyyy-mm-dd') " +
I tried it as :
" cob_Date =:cobDate "
but it didn't work either.
That cobDate is being declared as a LocalDate in the method signature implies that you already have that value in date format. If so, then the call to to_date() in the query is not needed. Try binding the LocalDate value directly:
#Query( value =" SELECT status "+
" FROM tb1 " +
" WHERE " +
" to_date(cob_Date,'dd-MON-yy') = :cobDate " +
" AND business_Day ='BD3' " +
" AND intra_day ='INTRA_06' " +
" AND datasource_name =:datasource" +
" AND upper(status) = 'COMPLETED' " +
" AND frequency = 'MONTHLY' " +
" AND processed = 'Y' " +
" ORDER BY create_date desc FETCH FIRST 1 rows only"
, nativeQuery=true)
List<String> getImpalaJobStatus(#Param("intraDay") String intraDay,
#Param("businessDay") String businessDay,
#Param("cobDate") LocalDate cobDate,
#Param("datasource") String datasource);
Note that your Oracle JBDC driver should know how to marshall the LocalDate value to the database such that the query works.
When adding "NULLS LAST" on the following query I'm getting the exception below:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The value is not set for the parameter number 11.
If I remove the NULLS LAST everything works fine
If I remove the CASE WHEN code and order by just one specific column it works with the NULLS LAST, but I need all the columns on the CASE WHEN.
#Query("SELECT c FROM ClassSpecificationTableEntity c"
+ " LEFT JOIN c.owner o "
+ " LEFT JOIN c.domain d "
+ "WHERE ISNULL(c.classStructure.classification.description, '') LIKE :SEARCH "
+ " OR ISNULL(c.classStructure.description, '') LIKE :SEARCH "
+ " OR ISNULL(d.description, '') LIKE :SEARCH "
+ " OR ISNULL(o.description, '') LIKE :SEARCH "
+ " OR ISNULL(c.measurementUnit, '') LIKE :SEARCH "
+ " OR ISNULL(c.defaultValue, '') LIKE :SEARCH "
+ " OR ISNULL(c.dataType, '') LIKE :SEARCH "
+ " OR ISNULL(c.tooltip, '') LIKE :SEARCH "
+ " ORDER BY "
+ " CASE :ORDERBY" +
" WHEN 0 THEN c.classStructure.classification.description " +
" WHEN 1 THEN c.assetAttribId " +
" WHEN 2 THEN c.dataType " +
" WHEN 3 THEN c.measurementUnit " +
" WHEN 4 THEN c.domain.description " +
" WHEN 5 THEN c.owner.description " +
" WHEN 6 THEN c.defaultValue " +
" WHEN 7 THEN c.tooltip " +
" END DESC NULLS LAST"
)
Page<ClassSpecificationTableEntity> findByLikeSearchDESC(#Param(value="SEARCH") final String searchCrit, final Pageable pageable, #Param(value="ORDERBY") final String orderBy);
There is no NULLS LAST syntax is T-SQL.
If you want to order NULL values last the common way is to use a CASE expression or IIF:
--CASE Expression
CASE WHEN {expression} IS NULL THEN 1 ELSE 0 END
--IIF funciton (which is actually a shorthand CASE expression)
IIF({Expression} IS NULL, 1, 0)
If you have a complicated expression, that you want to order the NULL values last for, and then the expression, and that expression does not appear in the SELECT (so cannot be referenced by its Alias), then you can move the expression to the FROM, to avoid typing the expression multiple times:
FROM ...
JOIN ...
LEFT JOIN ...
...
CROSS APPLY (VALUES({Expression}))V(Alias)
WHERE ...
ORDER BY IIF(V.Alias IS NULL,1,0),
V.Alias
Dear Openstack community,
I have a native query like the one below:
List<Tuple> tuples = em.createNativeQuery("(SELECT"
+ " er.id er_id, er.globalId glboalId, er.rma rma, er.trackingNumber trackingNumber, er.returnMethod returnMethod, er.invoice invoice, er.carrier_shipment_id carrier_shipment_id, er.carrier_label_request_id carrier_label_request_id, er.notes er_notes, er.pickupDateTime er_pickupDateTime"
+ ", ca.id carrier_id, ca.firstName carrier_fn, ca.email carrier_email"
+ ", sh.id shipper_id, sh.firstName shipper_fn, sh.email shipper_email"
+ ", co.id consignee_id, co.firstName consignee_fn, co.email consignee_email"
+ ", dest.id destination_id, dest.firstName destination_fn, dest.email destinaton_email"
+ ", pi.id pi_id, pi.price price, pi.scanDateTime scanDateTime, pi.returnAction returnAction, pi.globalCondition globalCondition, pi.reasonToReturn reasonToReturn, pi.rule rule, pi.refundAction refundAction, pi.newSku newSku, pi.wrongSku wrongSku, pi.returnStartDate returnStartDate, pi.returnEndDate returnEndDate, pi.weight weight, pi.notes pi_notes"
+ " FROM ereturn er"
+ " JOIN product_item pi ON pi.ereturn = er.id"
+ " JOIN user sh ON er.shipper = sh.id"
+ " JOIN user ca ON er.carrier = ca.id"
+ " JOIN user co ON er.consignee = co.id"
+ " JOIN user dest ON er.destination = dest.id"
+ " WHERE"
+ " er.trackingNumber = :scanValue)"
+ " UNION ALL"
+ " (SELECT"
+ " er.id er_id, er.globalId glboalId, er.rma rma, er.trackingNumber trackingNumber, er.returnMethod returnMethod, er.invoice invoice, er.carrier_shipment_id carrier_shipment_id, er.carrier_label_request_id carrier_label_request_id, er.notes er_notes, er.pickupDateTime er_pickupDateTime"
+ ", ca.id carrier_id, ca.firstName carrier_fn, ca.email carrier_email"
+ ", sh.id shipper_id, sh.firstName shipper_fn, sh.email shipper_email"
+ ", co.id consignee_id, co.firstName consignee_fn, co.email consignee_email"
+ ", dest.id destination_id, dest.firstName destination_fn, dest.email destinaton_email"
+ ", pi.id pi_id, pi.price price, pi.scanDateTime scanDateTime, pi.returnAction returnAction, pi.globalCondition globalCondition, pi.reasonToReturn reasonToReturn, pi.rule rule, pi.refundAction refundAction, pi.newSku newSku, pi.wrongSku wrongSku, pi.returnStartDate returnStartDate, pi.returnEndDate returnEndDate, pi.weight weight, pi.notes pi_notes"
+ " FROM ereturn er"
+ " JOIN product_item pi ON pi.ereturn = er.id"
+ " JOIN user sh ON er.shipper = sh.id"
+ " JOIN user ca ON er.carrier = ca.id"
+ " JOIN user co ON er.consignee = co.id"
+ " JOIN user dest ON er.destination = dest.id"
+ " WHERE"
+ " er.rma = :scanValue)"
+ " UNION ALL"
+ " (SELECT"
+ " er.id er_id, er.globalId glboalId, er.rma rma, er.trackingNumber trackingNumber, er.returnMethod returnMethod, er.invoice invoice, er.carrier_shipment_id carrier_shipment_id, er.carrier_label_request_id carrier_label_request_id, er.notes er_notes, er.pickupDateTime er_pickupDateTime"
+ ", ca.id carrier_id, ca.firstName carrier_fn, ca.email carrier_email"
+ ", sh.id shipper_id, sh.firstName shipper_fn, sh.email shipper_email"
+ ", co.id consignee_id, co.firstName consignee_fn, co.email consignee_email"
+ ", dest.id destination_id, dest.firstName destination_fn, dest.email destinaton_email"
+ ", pi.id pi_id, pi.price price, pi.scanDateTime scanDateTime, pi.returnAction returnAction, pi.globalCondition globalCondition, pi.reasonToReturn reasonToReturn, pi.rule rule, pi.refundAction refundAction, pi.newSku newSku, pi.wrongSku wrongSku, pi.returnStartDate returnStartDate, pi.returnEndDate returnEndDate, pi.weight weight, pi.notes pi_notes"
+ " FROM ereturn er"
+ " JOIN product_item pi ON pi.ereturn = er.id"
+ " JOIN user sh ON er.shipper = sh.id"
+ " JOIN user ca ON er.carrier = ca.id"
+ " JOIN user co ON er.consignee = co.id"
+ " JOIN user dest ON er.destination = dest.id"
+ " WHERE"
+ " er.invoice = :scanValue)", Tuple.class)
.setParameter("scanValue", scanValue)
.getResultList();
While running this query I am getting the following error:
SEVERE: Servlet.service() for servlet [jersey-servlet] in context with path [/returnitRest] threw exception [javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111] with root cause
org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111
at org.hibernate.dialect.TypeNames.get(TypeNames.java:70)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:101)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:683)
at org.hibernate.loader.custom.JdbcResultMetadata.getHibernateType(JdbcResultMetadata.java:77)
at org.hibernate.loader.custom.ScalarResultColumnProcessor.performDiscovery(ScalarResultColumnProcessor.java:45)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:482)
at org.hibernate.loader.Loader.processResultSet(Loader.java:2214)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2170)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1931)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1893)
at org.hibernate.loader.Loader.doQuery(Loader.java:938)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2692)
at org.hibernate.loader.Loader.doList(Loader.java:2675)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2507)
at org.hibernate.loader.Loader.list(Loader.java:2502)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:335)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:2200)
at org.hibernate.internal.AbstractSharedSessionContract.list(AbstractSharedSessionContract.java:1016)
at org.hibernate.query.internal.NativeQueryImpl.doList(NativeQueryImpl.java:152)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414)
at org.hibernate.query.Query.getResultList(Query.java:146)
at returnitRest.EreturnDAO.fetchBySalesOrderOrRmaOrTrackingNumber(EreturnDAO.java:1088)
at endpoints.EreturnResource.getByGlobalId(EreturnResource.java:466)
...
If the UNION ALL and/or fields pi.returnStartDate and pi.returnEndDate are removed, then the query runs fine.
Please note I am using nativeQuery and not JPA/JPQL
Could someone please help me to understand what am I doing wrong?
thank you very much
Manuel
I keep getting the following error: "could not locate named parameter [articleCommentId]" but it doesn't make sense to me because to me the named parameter is very much in place.
public ArticleCommentForDisplay getCommentByArticleCommentId(BigInteger articleCommentId) {
String queryString = "select c.article_comment_id, "
+ " c.article_id, "
+ " c.parent_comment_id, "
+ " p.nickname, "
+ " c.title, "
+ " c.comment, "
+ " c.person_id, "
+ " c.confirmed_user, "
+ " c.comment_depth, "
+ " c.moderation_rank, "
+ " c.moderation_reason, "
+ " c.hide, "
+ " c.hide_reason, "
+ " c.session_id, "
+ " c.confirmation_uuid, "
+ " c.created_timestamp, "
+ " c.created_by_id, "
+ " c.updated_timestamp, "
+ " c.updated_by_id, "
+ " c.update_action, "
+ " null as comment_path "
+ "from article_comment c "
+ " join person p "
+ " on p.person_id = c.person_id "
+ "where c.article_comment_id = :articleCommentId; ";
Query query = em.createNativeQuery(queryString, "ArticleCommentMap");
query.setParameter("articleCommentId", articleCommentId);
List <ArticleCommentForDisplay> articleComments = new ArrayList<>();
articleComments = query.getResultList();
ArticleCommentForDisplay theComment = articleComments.get(0);
return (theComment);
}
Here is an extract of the stack trace with the relevant error:
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: could not locate named parameter [articleCommentId]
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:379)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72)
at com.extremelatitudesoftware.content.ArticleCommentFacade.getCommentByArticleCommentId(ArticleCommentFacade.java:293)
I bet it is due to the extra ; in your query string.
SQL/HQL does not need to be terminated by semicolon
The named parameters is not defined for native queries in JPA Specification.
Replace
where c.article_comment_id = :articleCommentId;
with
where c.article_comment_id = ?1;
....
query.setParameter(1, articleCommentId)
Mine was an extra ' in the sql query. Oh my gosh, kept looking until my eyes nearly pooooopped out `-)
So, ensure that you don't have anything "extra" in your query, make sure that your (, ", ' etc...have matching pairs, because the error message in that case is not relevant and has nothing to do with your named parameter! JPA is right as it could not locate it, but that's because something else in your query is messing up...
You can also use it like this
where c.article_comment_id = ?,
and c.any_other_field = ?;
....
query.setParameter(1, articleCommentId)
query.setParameter(2, anyOtherValue)
it will take it by sequence.
And you can also give numbers like
where c.article_comment_id = ?1,
and c.any_other_field = ?2;
....
query.setParameter(1, articleCommentId)
query.setParameter(2, anyOtherValue)
If you are using named parameter at end of your query the remove the ; from your query
In my case, I didn't add the extra space after the named parameter.
example:
+ "WHERE\n" + " s.something = 'SOME'\n" + "START WITH\n"
+ " s.country_type = :countryName" + "CONNECT BY\n"
changed to (notice the space after named parameter :countryName
+ "WHERE\n" + " s.something = 'SOME'\n" + "START WITH\n"
+ " s.country_type = :countryName " + "CONNECT BY\n"
I have a follow up to complicated mysql question that I recently asked: Show the ten first contacts that I have recieved message
Now I know that it is missing something, my last question was:
I want to create Sql statement that
show the ten first contacts that I
have recieved message from along with
their latest sent message and time.
The table columns is messageId,
message, fromProfileId, toProfileId,
timeStamp and table is called
messages. The database is Mysql and
Java is the language. But I want this
to happen in one single sql statement.
What's missing is that I want to show the message I've sent also, but it should be grouped with the messages that I've recieved from the user I've sent to:
ten first contacts that I have
received message from or sent to along
with their latest sent message and
time.
Little complicated to understand? Ok. think like this. the quoted first sql statement above only show messages that I reveived from. but what if I send a message? That message will never show up.
This is my code, but I failed to succed(look at where I marked the comment):
"SELECT M2.messageProfileId, profiles.profileMiniature, profiles.firstName, profiles.lastName, profiles.timeFormat, lastMessages.message, lastMessages.timeStamp " +
"FROM (" +
" SELECT IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) AS messageProfileId, " +
" max(M1.timeStamp) AS lastMessageTime " +
" FROM messages AS M1 " +
" WHERE M1.toProfileId = ? " +
" OR M1.fromProfileId = ? " +
" GROUP BY IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) " +
" ORDER BY max(M1.timeStamp) DESC " +
" LIMIT 10 " +
" ) AS M2 " +
"INNER JOIN messages AS lastMessages " +
"ON (" +
" lastMessages.timeStamp = M2.lastMessageTime " +
"AND lastMessages.fromProfileId = M2.messageProfileId" +//This to be like the if statements above, but how?
" )" +
"INNER JOIN profiles " +
"ON M2.messageProfileId = profiles.profileId ";
UPDATE:
All question marks in the above code will be replaced with a a same id, for example 27.
UPDATE:
You just have to solve one line now. Look at the commented line above. I dont know how to make if statement in where clause?
Ok figured it out myself
"SELECT M2.messageProfileId, profiles.profileMiniature, profiles.firstName, profiles.lastName, profiles.timeFormat, lastMessages.message, lastMessages.timeStamp " +
"FROM (" +
" SELECT IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) AS messageProfileId, " +
" max(M1.timeStamp) AS lastMessageTime " +
" FROM messages AS M1 " +
" WHERE (M1.toProfileId = ? " +
" OR M1.fromProfileId = ?) " +
" GROUP BY IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) " +
" ORDER BY max(M1.timeStamp) DESC " +
" LIMIT 10 " +
" ) AS M2 " +
"INNER JOIN messages AS lastMessages " +
"ON (" +
" lastMessages.timeStamp = M2.lastMessageTime " +
"AND (" +
" lastMessages.fromProfileId = M2.messageProfileId " +
"OR lastMessages.toProfileId = M2.messageProfileId " +
" )" +
" )" +
"INNER JOIN profiles " +
"ON M2.messageProfileId = profiles.profileId ";