java.util.UnknownFormatConversionException: Conversion - java

I wrote a script to orchestrate a query on our hive cluster. And this is the place where the error happened:
Result<Record> result = client.doWithRetry(new SQLClient.JooqSQLFunction<Result<Record>>() {
#Override
public Result<Record> apply(Connection conn, DSLContext jooq) throws SQLException, DataAccessException {
return jooq.fetch(String.format(
"select s.name as season_name, r.name as round_name, " +
" g.uuid, g.name, g.create_time, "+
" (select count(*) from picks_questions q where q.round_uuid=r.uuid) as questions_in_round, "+
" (select group_concat(du.yinz_id) from drops_entries e inner join drops_users du on du.uuid=e.user_uuid where g.uuid=e.drop_uuid and e.create_time<r.end_time) as member_yinz_ids, "+
" (select count(*) from drops_entries e inner join drops_users du on du.uuid=e.user_uuid where g.uuid=e.drop_uuid and e.create_time<r.end_time) as member_count, "+
" (select count(*) from drops_messages m where m.drop_uuid=g.uuid and m.send_time>=r.start_time and m.send_time<r.end_time) as messages_sent "+
" from picks_seasons s "+
" inner join picks_rounds r on r.season_uuid=s.uuid "+
" inner join drops g on g.create_time<r.end_time "+
" where g.name not like 'ADMIN_DROP:%' and g.name<>'' "+
" and s.uuid in "+
" ( "+
" select uuid from picks_seasons "+
" where "+
" unix_timestamp('%s') >= unix_timestamp(start_time) " +
" AND " +
" unix_timestamp('%s') < unix_timestamp(end_time) " +
" );",
sqlDTF.print(seg.getStartingInstant()),
sqlDTF.print(seg.getEndingInstant())
));
}
}
I didn't use "'''" at all. Any ideas what went wrong?
Error Traceback:
java.lang.RuntimeException: java.lang.RuntimeException: java.util.UnknownFormatConversionException: Conversion = '''
at workflows.AbstractCopperWorkflow.main(AbstractCopperWorkflow.java:394) ~[na:na]

% Mark is a reserved character in format string of Java. To escape this, we should use %% instead of %.

Related

Hibernate Error: could not extract ResultSet

I have this error in my code:
"Request processing failed; nested exception is javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not extract ResultSet] con causa raíz
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-206,
SQLSTATE=42703, SQLERRMC=INVOICESEL2_.CODE_K, DRIVER=4.14.88"
I am not able to find the error, I know that the SQL code -206 refers to An object is specified in a context where it is not valid.
My code is this:
public InvoiceSeller getSellerByEmail(String email, String debtorCode) {
String qString = "SELECT d FROM " + InvoiceSeller.class.getSimpleName() + " d "
+ " INNER JOIN "+ InvoiceSellerContact.class.getSimpleName() + " sc "
+ " ON d.code = sc.invoiceSeller.code AND d.invoiceDebtor.code = sc.invoiceSeller.invoiceDebtor.code "
+ " INNER JOIN "+ Contact.class.getSimpleName() + " c ON sc.contact.id = c.id "
+ " INNER JOIN " + ActiveRegisterMaster.class.getSimpleName() + " a "
+ " ON d.code = a.code AND d.invoiceDebtor.code = a.invoiceDebtor "
+ " WHERE a.tableName = :tablename AND d.invoiceDebtor.code = :debtorCode "
+ " AND c.email = :email AND d.status = :status";
TypedQuery<InvoiceSeller> query = this.em.createQuery(qString, InvoiceSeller.class);
System.out.println(qString);
System.out.println(query.getFirstResult());
query.setParameter("debtorCode", debtorCode);
query.setParameter("email", email);
query.setParameter("tablename", InvoiceSeller.TABLENAME);
query.setParameter("status", "A");
InvoiceSeller seller = query.getSingleResult();
System.out.println(seller.toString());
return seller;
}
Thanks!
Your HQL is wrong, remember that HQL sintax is different from SQL and when you call this.em.createQuery you are trying to create a HQL.
So, your HQL should be something like this:
String qString = "SELECT d FROM " + InvoiceSeller.class.getSimpleName() + " d "
+ " INNER JOIN "+ InvoiceSellerContact.class.getSimpleName() + " sc "
+ " INNER JOIN "+ Contact.class.getSimpleName() + " c "
+ " INNER JOIN " + ActiveRegisterMaster.class.getSimpleName() + " a "
+ " WHERE a.tableName = :tablename AND d.invoiceDebtor.code = :debtorCode "
+ " AND c.email = :email AND d.status = :status";
+ " AND c.email = :email AND d.status = :status";
Note that i removed the ON keywords after INNER JOIN, beacuse HQL don't need it.

Common table expression, with a starting with a values statement gives error in java

I've this CTE which I'd implement in Java:
It's running on an IBM Iseries 7.3 DB2 machine.
WITH params (from_date, to_date, outlet, product_number)
AS (
values(TO_DATE('01.11.2018', 'DD.MM.YYYY'),
TO_DATE('18.12.2018', 'DD.MM.YYYY'),
'BLK' ,
49 )
),
product
AS (
SELECT DISTINCT cpp.competitor_products_id product
FROM yxdb.competitor_product_prices cpp
INNER JOIN yxdb.competitor_products_comparisons cpc ON cpc.competitor_products_id = cpp.competitor_products_id
AND cpc.deleted = 0
INNER JOIN yxdb.outlets o ON o.outlets_id = cpc.outlets_id
AND o.deleted = 0
INNER JOIN params ON cpp.price_date > params.from_date
AND cpc.product_number = params.product_number
AND o.short_name = params.outlet
WHERE cpp.deleted = 0
)
select * from product;
It's a lot longer, so the params table is used several times.
When implementing it in Java, I replace the hardcoded dates and other parameters in Java as ?1, ?2 etc. I've also tried with named parameters, none works. They all give [SQL0418] Use of parameter marker or NULL not valid.
Java Code snippet:
#RepositoryRestResource
public interface CompetitorPriceDateRepository extends JpaRepository<CompetitorPriceDateEntity, Long> {
#Query(value = "WITH params (from_date, to_date, outlet, product_number) "
+ " AS ( "
+ " values(TO_DATE( :fromDate , 'DD.MM.YYYY'), "
+ " TO_DATE( :toDate , 'DD.MM.YYYY'), "
+ " :outlet , "
+ " :productNumber ) "
+ " ), "
+ " product "
+ " AS ( "
+ " SELECT DISTINCT cpp.competitor_products_id product "
+ " FROM yxdb.competitor_product_prices cpp "
+ " INNER JOIN yxdb.competitor_products_comparisons cpc ON +" cpc.competitor_products_id = cpp.competitor_products_id "
+ " AND cpc.deleted = 0 "
+ " INNER JOIN yxdb.outlets o ON o.outlets_id = cpc.outlets_id "
+ " AND o.deleted = 0 "
+ " INNER JOIN params ON cpp.price_date > params.from_date "
+ " AND cpc.product_number = params.product_number "
+ " AND o.short_name = params.outlet "
+ " WHERE cpp.deleted = 0 "
+ " ) "
+ " select * from product ",nativeQuery = true)
List<CompetitorPriceDateEntity> findAllInterpolatedByDates(
#Param("productNumber") Integer productNumber,
#Param("outlet") String outlet,
#Param("fromDate") String fromDate,
#Param("toDate") String toDate
);
Without the stack trace I dont' have any aidea what's wrong with your query. SQL seems solid.
Try with a named native query
#Entity
#NamedNativeQuery(
name = “competitor.findProducts.byDateOutletProductnumber",
query = "WITH params (from_date, to_date, outlet, product_number) "
+ " AS ( "
+ " values(TO_DATE( :fromDate , 'DD.MM.YYYY'), "
+ " TO_DATE( :toDate , 'DD.MM.YYYY'), "
+ " :outlet , "
+ " :productNumber ) "
+ " ), "
+ " product "
+ " AS ( "
+ " SELECT DISTINCT cpp.competitor_products_id product "
+ " FROM yxdb.competitor_product_prices cpp "
+ " INNER JOIN yxdb.competitor_products_comparisons cpc ON +" cpc.competitor_products_id = cpp.competitor_products_id "
+ " AND cpc.deleted = 0 "
+ " INNER JOIN yxdb.outlets o ON o.outlets_id = cpc.outlets_id "
+ " AND o.deleted = 0 "
+ " INNER JOIN params ON cpp.price_date > params.from_date "
+ " AND cpc.product_number = params.product_number "
+ " AND o.short_name = params.outlet "
+ " WHERE cpp.deleted = 0 "
+ " ) "
+ " select * from product ",
hints = {
#QueryHint(name = "org.hibernate.cacheable", value = "true") })
public class CompetitorPriceDateEntity { ... }
pro bonus 1: Named queries are sort of precompiled, so jpa doesn't need to compile the query into a executable criteria every time it gets called.
pro bonus 2: Query hint cacheable or eclipselink equivalent

Trouble rewriting an SQL query into HQL query

So, here is my original query in SQL:
SELECT o.offering_number,
o.english_description,
o.french_description,
fop.price_amount,
fop2.price_amount,
fop.price_type_code,
fop.offering_id,
fop2.offering_id
from facility_offering_price fop
join offering o on fop.offering_id = o.offering_id
inner join
(select
fop1.offering_id,
fop1.price_amount
from facility_offering_price fop1
WHERE fop1.price_type_code = 5
AND fop1.price_status_code = 1
) fop2 on fop.offering_id = fop2.offering_id
WHERE fop.price_start_date = '15-10-28'
AND fop.price_status_code IN (1,2)
/*AND (price_status_code IS NULL)*/
AND fop.price_type_code = 5
/*AND (o.offering_number IS NULL)*/
ORDER BY o.offering_number ASC, fop.price_sequence_number ASC;
Here is the query above in HQL:
#Query("SELECT new com.frontier.dto.productprice.PendingPriceProduct("
+ " fop.facilityPhysicalOffering.offeringNumber,"
+ " fop.facilityPhysicalOffering.offering.description.englishDescription,"
+ " fop.facilityPhysicalOffering.offering.description.frenchDescription,"
+ " fop.priceAmount,"
+ " fop2.priceAmount,"
+ " fop.priceStatusCode"
+ ")"
+ " from FacilityOfferingPrice fop"
+ " INNER JOIN (SELECT fop1.offeringId, fop1.priceAmount FROM FacilityOfferingPrice fop1 WHERE "
+ " fop1.id.priceTypeCode = com.frontier.domain.type.PriceType.REG_RETAIL_PRICE"
+ " AND fop1.priceStatusCode = com.frontier.domain.type.OfferingPriceSts.CURRENT" +
" ) fop2 on fop.offeringId = fop2.offeringId"
+ " WHERE fop.priceStartDate = :priceStartDate"
+ " AND fop.priceStatusCode IN (:priceStatusCodes)"
+ " AND (:priceStatusCode IS NULL OR fop.priceStatusCode = :priceStatusCode)"
+ " AND fop.id.priceTypeCode = com.frontier.domain.type.PriceType.REG_RETAIL_PRICE"
+ " AND (:fromOfferingNumber IS NULL OR fop.facilityPhysicalOffering.offeringNumber >=:fromOfferingNumber)"
+ " ORDER BY fop.facilityPhysicalOffering.offeringNumber ASC, fop.id.priceSequenceNumber ASC")
List<PendingPriceProduct> findPendingPriceProducts(
#Param("priceStartDate") LocalDate priceStartDate,
#Param("priceStatusCodes") List<OfferingPriceSts> priceStatusCodes,
#Param("priceStatusCode") OfferingPriceSts priceStatusCode,
#Param("fromOfferingNumber") Long fromOfferingNumber,
Pageable pageable);
The error message: unexpected token: ( near line 1, column 372.
So, something is wrong with the join syntax. It was all good before I replaced the subquery with this join.
I would appreciate your help.
UPDATE:
New Query:
#Query("SELECT "
+ " new com.frontier.dto.productprice.PendingPriceProduct("
+ " fop.facilityPhysicalOffering.offeringNumber,"
+ " fop.facilityPhysicalOffering.offering.description.englishDescription,"
+ " fop.facilityPhysicalOffering.offering.description.frenchDescription,"
+ " fop.priceAmount,"
+ " fop1.priceAmount,"
+ " fop.priceStatusCode"
+ ")"
+ " from FacilityOfferingPrice fop"
+ " INNER JOIN FacilityOfferingPrice fop1 on fop.offeringId = fop1.offeringId"
+ " WHERE fop.priceStartDate = :priceStartDate"
+ " AND fop.priceStatusCode IN (:priceStatusCodes)"
+ " AND (:priceStatusCode IS NULL OR fop.priceStatusCode = :priceStatusCode)"
+ " AND fop.id.priceTypeCode = com.frontier.domain.type.PriceType.REG_RETAIL_PRICE"
+ " AND (:fromOfferingNumber IS NULL OR fop.facilityPhysicalOffering.offeringNumber >=:fromOfferingNumber)"
+ " ORDER BY fop.facilityPhysicalOffering.offeringNumber ASC, fop.id.priceSequenceNumber ASC")
List<PendingPriceProduct> findPendingPriceProducts(
#Param("priceStartDate") LocalDate priceStartDate,
#Param("priceStatusCodes") List<OfferingPriceSts> priceStatusCodes,
#Param("priceStatusCode") OfferingPriceSts priceStatusCode,
#Param("fromOfferingNumber") Long fromOfferingNumber,
Pageable pageable);
New error:
Path expected for join!, `InvalidPathException: Invalid path: 'fop1.priceAmount'
I'm not sure you can write subqueries like this in HQL, and by the way, do you really need a subquery at all? If you rewrite your initial query like that
SELECT o.offering_number,
o.english_description,
o.french_description,
fop.price_amount,
fop1.price_amount,
fop.price_type_code,
fop.offering_id,
fop1.offering_id
from facility_offering_price fop
join offering o on fop.offering_id = o.offering_id
inner join facility_offering_price fop1
on fop.offering_id = fop1.offering_id
WHERE fop.price_start_date = '15-10-28'
AND fop.price_status_code IN (1,2)
/*AND (price_status_code IS NULL)*/
AND fop.price_type_code = 5
/*AND (o.offering_number IS NULL)*/
AND fop1.price_type_code = 5
AND fop1.price_status_code = 1
ORDER BY o.offering_number ASC, fop.price_sequence_number ASC;
The translation to HQL should be pretty straightforward.

HSQLDB: Encountered a duplicated sql alias

When I execute this query using a self-join from my java program
Query query = session.createSQLQuery("SELECT DISTINCT * " +
"FROM lerneinheit AS le1 JOIN lerneinheit AS le2 " +
"ON le1.datum = le2.datum AND le1.pid = le2.pid " +
" WHERE " +
" le1.datum BETWEEN '2016-10-20' AND '2016-10-20' AND " +
" le1.pid = 3 AND " +
" (le1.abgesagtrechtzeitig = false OR le1.nichtabgesagt = true OR le1.erschienen=true) AND " +
" (le2.abgesagtrechtzeitig = false OR le2.nichtabgesagt = true OR le2.erschienen=true) AND " +
" le1.lernid!= le2.lernid AND " +
" (le2.beginn+1 BETWEEN le1.beginn AND le1.ende OR le2.ende-1 BETWEEN le1.beginn AND le1.ende) " +
" ORDER BY le1.beginn");
I get the following error:
org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias [LERNID] during auto-discovery of a native-sql query
Although it works fine if I do this from phpAdmin. Everything I found on that topic wasn't helpful at all. Anyone got any idea how to solve that?
It may occurred when there are two or more column/alias exists with the SAME NAME in your select query.
Like...
Select A.NAME, A.ADDRESS, B.NAME, B.AGE from TABLE_A A join TABLE_B B on A.SOME_ID = B.SOME_ID;
Encountered a duplicated sql alias [NAME] during auto-discovery of a native-sql query will show.
I'm not sure but the HQL equivalent for != is <>, so you should write "le1.lernid <> le2.lernid AND"
And by the way I recommend :
Query query = session.createSQLQuery("SELECT DISTINCT * " +
"FROM lerneinheit AS le1 JOIN lerneinheit AS le2 " +
"ON le1.datum = le2.datum AND le1.pid = le2.pid " +
" WHERE " +
" le1.datum BETWEEN :dateMin AND :dateMax AND " +
" le1.pid = :le1Pid AND " +
" (le1.abgesagtrechtzeitig = false OR le1.nichtabgesagt = true OR le1.erschienen = true) AND " +
" (le2.abgesagtrechtzeitig = false OR le2.nichtabgesagt = true OR le2.erschienen = true) AND " +
" le1.lernid != le2.lernid AND " +
" (le2.beginn + 1 BETWEEN le1.beginn AND le1.ende OR le2.ende - 1 BETWEEN le1.beginn AND le1.ende) " +
" ORDER BY le1.beginn");
query.setParametter("dateMin", "2016-10-20");
query.setParametter("dateMax", "2016-10-20");
query.setParametter("le1Pid", 3);

How to use CASE WHEN in Hibernate Where clause

Plase give example for using CASE WHEN in HQL.
I have used following query in my code.
int receiptNumber = 100;
String hql = "SELECT b FROM OOPExtract as b "
+"WHERE "
+" b.tranStatId =" +receiptNumber+ " AND "
+" b.orderType IN ('EMERGENCY', 'PLENARY', 'PETITION','EXTENSION','MOTION') AND "
+" CASE WHEN b.orderType == 'MOTION' " `enter code here`
+ "THEN "
+" b.status = 'MOTION_SIGNED' "
+" ELSE "
+" b.status LIKE '%%' "
+" END "
+" ORDER BY b.oopExtractId DESC";
But when it run it's generate following exception
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: = .....
I've used the following query in a working project. Could use it as a template :)
"SELECT "
+ "CASE WHEN smth.status != 'BATMAN' THEN ... "
+ "ELSE (SELECT ... FROM ... WHERE ... ORDER BY ... DESC limit 1) "
+ "END, "
+ "next_field, "
+ "CASE WHEN smth.status == 'BATMAN' THEN ... "
+ "ELSE ... "
+ "END, "
+ "final_field_which_doesent_have_a_case_logic"
+ "FROM ... the_rest_of_the_normal_query";
This one works with Hibernate 4/JPA and Spring 4 as well!
select
limite
from
Limite limite
join
fetch limite.limiteEnqs enq
join
fetch enq.limiteValors valor
where
limite.id = :limiteId
and :dataReferencia between valor.dtIniVig and valor.dtFimVig
and enq.vrAtributo1 = case limite.atributoId1
when 8 then :produtoId
else enq.vrAtributo1
end
Please try this. Hope it Work.
"SELECT b FROM OOPExtract as b WHERE "
+" b.tranStatId =" +receiptNumber+ " AND "
+" b.orderType IN ('EMERGENCY', 'PLENARY', 'PETITION','EXTENSION','MOTION') AND "
**+" CASE WHEN b.orderType 'MOTION' " `enter code here`
+ "THEN 'MOTION_SIGNED' "
+" ELSE "**
+" b.status LIKE '%%' "
+" END "
+" ORDER BY b.oopExtractId DESC";

Categories

Resources