HQL createQuery throws NullPointerException when create new object in query - java

I am trying to create new object from the result set of HQL query but it is throwing NullPointerException at session.createQuery()
Could someone please show me any flaw in the query that I created?
The idea is to return the type/area/reason along with their count and then create new CasesOverview object with these values.
StringBuilder hql = new StringBuilder("SELECT NEW CasesOverviewDTO(:filterColumnString, Math.toIntExact(count(c.id)), :filter) ");
hql.append("FROM Case AS c ");
hql.append("where c.site.id = :siteId and c.status ");
if(isOpen) {
hql.append("!= :close and createdDate > :startDate and createdDate < :endDate ");
} else {
hql.append("= :close and closedDate > :startDate and closedDate < :endDate ");
}
hql.append("group by :filterColumn");
Query query = exeQuery(hql.toString());
switch(filter) {
case TYPE:
query.setParameter("filterColumnString", "c.area.toString()");
query.setParameter("filterColumn", "c.area");
break;
case CASE_TYPE:
query.setParameter("filterColumnString", "c.type.toString()");
query.setParameter("filterColumn", "c.type");
break;
case RESOLUTION:
query.setParameter("filterColumnString", "c.reason.toString()");
query.setParameter("filterColumn", "c.reason");
break;
}
query.setParameter("filter", filter);
query.setParameter("siteId", siteId);
query.setParameter("close", "CLOSED");
query.setParameter("startDate", startDate);
query.setParameter("endDate", endDate);
In the createQuery method, error is thrown:
Caused by: java.lang.NullPointerException
at org.hibernate.hql.internal.ast.tree.ConstructorNode.formatMissingContructorExceptionMessage(ConstructorNode.java:201)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:193)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:158)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1095)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2328)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2194)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1476)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:573)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at com.essensys.bluefin.dao.hibernate.HibernateGenericDao.exeQuery(HibernateGenericDao.java:411)

From the stack trace it looks like there's no constructor that would satisfy your CasesOverviewDTO(:filterColumnString, Math.toIntExact(count(c.id)), or if there is, it's not in the same package as the class the hql query is being created in, and therefore needs to be fully qualified (add the package name like new com.some.package.CasesOverviewDTO(args)). Can you please also post your CasesOverviewDTO ?

Related

Java SQL Resultset DataTypes

I’m a java novice and have been tinkering with an existing Proc. I’m attempting to perform an out.write on a value derived from a SQL resultset 'Grid_ProjectCode’, as shown here:
sStmt=null;rs=null;sql=null;
sStmt = conn.createStatement();
sql = "select Proj_Code, Placement_ACR, Category_ID, Alt_Aisle_Shelf, Placement_Start_Dt, Placement_End_Dt, Sales_Manager from DH_CURRENT_FUTURE_INVENTORY_VW where Placement_ACR in ('banFSI_ROI', 'banFSI','FSI')";
rs = sStmt.executeQuery(sql);
while ( rs.next() )
{
String Grid_ProjectCode = rs.getString("Proj_Code");
String Dup_Placement_ACR = rs.getString("Placement_ACR");
if (plCode.equalsIgnoreCase(Dup_Placement_ACR))
{
out.write("Dupe Found");
out.newLine();
out.write(Grid_ProjectCode);
out.newLine();
}
}
if(conn != null) { rs.close(); sStmt.close(); }
The Proc fails with the following error (runs as expected when the second out.write is removed/commented):
java.lang.ClassCastException: [Ljava.lang.Integer; incompatible with
[Ljava.lang.String;
The Proj_Code field referred to in the SQL query is an NVARCHAR2 defined in an Oracle Exadata schema.
The error suggests some sort of data type mismatch, but I’m not sure how this is can be fixed; would really appreciate some guidance.
Edited to include DDL for DH_CURRENT_FUTURE_INVENTORY_vw:
CREATE OR REPLACE FORCE VIEW "UNICA_F1"."DH_CURRENT_FUTURE_INVENTORY_VW" ("PROJ_CODE", "FLAG_PROJ_REQUEST", "OBJECT_ID", "UAP_GRID_ROW_ID", "PLACEMENT_IMPRESSIONS", "SUPPLIER_CATEGORY", "PLACEMENT_CLASH", "PLACEMENT_NAME", "PLACEMENT_AISLE_SHELF", "PLACEMENT_START_DT", "PLACEMENT_RATE", "PLACEMENT_SIZE", "PLACEMENT_END_DT", "PLACEMENT_DURATION", "PLACEMENT_ACR", "SALES_VALUE", "NOTES", "STATUS", "AD_SERVER", "UNIT_NR", "SORT_ORDER", "CATEGORY_ID", "AISLE_SHELF_ID", "PLACEMENT_COUNT", "RETAIL_ACR", "ALT_AISLE_SHELF", "PLACEMENT_SIZE2", "PLACEMENT_SIZE3", "PLACEMENT_SIZE4", "PLACEMENT_SIZE5", "CREATIVE_YN", "CPM", "CREATIVE_SIZE", "PRODUCT_ID", "SALES_AREA", "IMPRESSION_GOAL", "CLIENT_CATEGORY", "CLIENT_SUB_CAT", "BRAND_NM", "FORMAT_DESC", "IMPRESSION_CPM", "IMPRESSION_VALUE", "CREATIVE_COST", "SIZE_DESC", "DELIVERY_PROCESS", "PACKAGE_FLAG", "PACK_ID", "RETARGETING_FLAG", "BATCH_FLAG", "BASE_COST", "DISCOUNT", "CATEGORY", "SALES_MANAGER") AS
Select
PROJ_CODE,
FLAG_PROJ_REQUEST,
OBJECT_ID,
UAP_GRID_ROW_ID,
PLACEMENT_IMPRESSIONS,
SUPPLIER_CATEGORY,
PLACEMENT_CLASH,
PLACEMENT_NAME,
PLACEMENT_AISLE_SHELF,
PLACEMENT_START_DT,
PLACEMENT_RATE,
PLACEMENT_SIZE,
PLACEMENT_END_DT,
PLACEMENT_DURATION,
PLACEMENT_ACR,
SALES_VALUE,
NOTES,
STATUS,
AD_SERVER,
UNIT_NR,
SORT_ORDER,
CATEGORY_ID,
AISLE_SHELF_ID,
PLACEMENT_COUNT,
RETAIL_ACR,
ALT_AISLE_SHELF,
PLACEMENT_SIZE2,
PLACEMENT_SIZE3,
PLACEMENT_SIZE4,
PLACEMENT_SIZE5,
CREATIVE_YN,
CPM,
CREATIVE_SIZE,
PRODUCT_ID,
SALES_AREA,
IMPRESSION_GOAL,
CLIENT_CATEGORY,
CLIENT_SUB_CAT,
BRAND_NM,
FORMAT_DESC,
IMPRESSION_CPM,
IMPRESSION_VALUE,
CREATIVE_COST,
SIZE_DESC,
DELIVERY_PROCESS,
PACKAGE_FLAG,
PACK_ID,
RETARGETING_FLAG,
BATCH_FLAG,
BASE_COST,
DISCOUNT,
CATEGORY,
SALES_MANAGER
from
(
select b.Proj_Code, b.Flag_Proj_Request, a.*, c.Category, d.Sales_Manager
from dh_ddp_inventory a
inner join uap_projects b on a.Object_ID = b.Project_ID
inner join dh_lkp_taxo_categ_vw c on a.Category_ID = c.Category_ID
inner join dh_ddp_Request d on a.Object_ID = d.Object_ID
where b.Flag_Proj_Request = 'Y' and a.Placement_End_Dt >= Current_date
and b.Proj_Code not in (select Proj_Code from uap_projects where Flag_Proj_Request = 'N')
Union
select b.Proj_Code, b.Flag_Proj_Request, a.*, c.Category, d.Sales_Manager
from dh_ddp_inventory a
inner join uap_projects b on a.Object_ID = b.Project_ID
inner join dh_lkp_taxo_categ_vw c on a.Category_ID = c.Category_ID
inner join dh_ddp_Request d on a.Object_ID = d.Object_ID
where b.Flag_Proj_Request = 'N' and a.Placement_End_Dt >= Current_date
)
Order By Proj_Code asc, Object_ID desc, Placement_Name asc;
Somewhere you do in some form or the other:
String[] stringArray = ...;
Integer[] intArray = (Integer[]) stringArray;
As [Ljava.lang.Integer =
array ([)
of class java.lang.Integer (L)
To drill down to the error:
try {
... code ...
} catch (ClassCastException e) {
e.printStackTrace(); // To System.err.
e.printStackTrace(System.out); // To System.out.
logger.error("OMG", e); // To logger if there is one.
throw e; // Act as is the exception was not thrown
}
Look at the stack trace, it also lists the source causing the error, together with the line number.

JPQL query does not return proper output, throws error

The following query throws me an error
#GET
#Path("findByStartEndVari/{startdate}/{enddate} ")
#Produces({"application/json"})
public List<Dailyrecords> findByStartEndVari(#PathParam("startdate") Date startdate, #PathParam("enddate") Date enddate)
{
TypedQuery<Dailyrecords> q = em.createQuery("SELECT d.painlevel, d.painlocation FROM Dailyrecords d WHERE d.submitdate BETWEEN :startdate AND :enddate ", Dailyrecords.class);
q.setParameter("startdate", startdate);
q.setParameter("enddate", enddate);
return q.getResultList();
}
It gives an output when I use SELECT d instead of particular attributes.
Throws a 500 internal server error.
Your current syntax is incorrect. If you want your JPQL query to return a DailyRecords object then you need to select the entire object:
TypedQuery<Dailyrecords> q = em.createQuery("SELECT d FROM Dailyrecords d WHERE d.submitdate BETWEEN :startdate AND :enddate ", Dailyrecords.class);
q.setParameter("startdate", startdate);
q.setParameter("enddate", enddate);
If you really want only specified columns, then you can try the following:
Query query = session.createQuery("SELECT d.painlevel, d.painlocation FROM Dailyrecords d WHERE d.submitdate BETWEEN :startdate AND :enddate");
List<Object[]> rows = query.list();
When you query individual columns, you will get back an Object[], with each entry in the array corresponding to one column. So in this case, the first entry would be the pain level, and the second the pain location.

Convert mysql query to JPQL query

How can i state the following mysql query in JPQL
select * from Price WHERE `valueDate` = (SELECT MAX(`valueDate`) FROM Price) and fundId = 2930
what i have tried is the following:
"select a from Price a where a.valueDate = select MAX(a.valueDate) and a.fund.id = :" +Price.QUERY_PARAM_FUND_ID
but get errors on that approach :
Caused by: <openjpa-2.3.0-r422266:1540826 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: "Encountered "MAX" at character 50, but expected: ["AND", "GROUP", "HAVING", "OR", "ORDER", <EOF>]." while parsing JPQL "select a from Price a where a.valueDate = select MAX(b.valueDate) from Price b and a.fund.id = :fundId"
I think it will work if you will added bracket before and after sub-query like.
"select a from Price a where a.valueDate = (select MAX(a.valueDate) from Price) and a.fund.id = :" +Price.QUERY_PARAM_FUND_ID
else let me say some thing related to hibernate implementation of JPA Specification.
If you have Hibernate model named 'Price' and you are going to do query through that model then. the HQL will be like that
try {
final StringBuilder qry = new StringBuilder();
qry.append(" SELECT")
.append(" FROM Price p")
.append(" WHERE p.valueDate = (SELECT MAX(pr.valueDate) FROM Price pr)")
.append(" AND p.fundId = :fundId");
return getJpaTemplate().execute(new JpaCallback() {
public Object doInJpa(EntityManager em)
throws PersistenceException {
Query q = em.createQuery(qry.toString());
q.setParameter("fundId", fundId);
return q.getResultList();
}
});
} catch (RuntimeException re) {}

Error with Hibernate HQL - unexpected token:

***import org.hibernate.Query;***
String hql = "FROM :className WHERE userCreate like ':userName'";
Query query = session.createQuery(hql);
query.setParameter("className", className);
query.setParameter("userName", userName);
List<Node> result = query.list();
And have an error
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: : near line 1, column 6 [FROM :className WHERE userCreate like ':userName']
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at com.SDC.DAO.DAOFileAndFolderService.findUserCreteFileOrFolder(DAOFileAndFolderService.java:36)
at com.SDC.View.Main.main(Main.java:57)
Exception in thread "main" java.lang.NullPointerException
at com.SDC.View.Main.main(Main.java:58)
You cannot use named parameters for Hibernate queries. You can get around this by manually appending the name of the table into your hql string. Your code would look instead like this:
String hql = "FROM " + className + " WHERE userCreate like ':userName'";
Query query = session.createQuery(hql);
query.setParameter("userName", userName);
List<Node> result = query.list();

invalid column type ~ Sending ArrayList<String> to a pl/sql createdNameQuery

This is related to a past question of mine.
I am receiving a List<Employee> and grabbing the ids from the Employee objects and putting them in an ArrayList<String> then sending that ArrayList as a parameter in the createdNameQuery. I am receiving an invalid column type sql exception. I tested the query in pl/sql developer and it returned fields. I have tried building out a string of ids by placing a coma between each id and sending that but, I received an exception from that attempt. I am curious if I have the query setup incorrectly or sending the data incorrectly.
function in my repository:
public List<RequestByRequester> getRequestsByRequesters(
List<Employee> employeeList)
throws NoDataFoundException {
List<String> idList = new ArrayList<String>();
for(Employee emp : employeeList) {
idList.add(emp.getId().toString());
}
log.debug("Input params[requesters=" + idList + "]");
List<RequestByRequester> resultList = getEm().createNamedQuery(
"requestByRequestor.getRequestsByRequesters", RequestByRequester.class)
.setParameter(1,idList)
.getResultList();
if(resultList == null || resultList.size() <= 0)
throw new NoDataFoundException("No requests found by requesters.");
else
return resultList;
}
My named query requestByRequestor.getRequestsByRequesters below:
#NamedNativeQuery(
name = "requestByRequestor.getRequestsByRequesters",
resultClass = RequestByRequester.class,
query = "SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER," +
" R.RQST_ID RQST_ID," +
" R.TITLE TITLE," +
" R.DESCRIPTION DESCRIPTION," +
" DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS" +
" FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP" +
" WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID" +
" AND EMP.EMPL_ID IN (?)" +
" ORDER BY 1, 5 DESC, 2"
)
EDIT: Adding exceptions as requested.
This exception when I use :ids in the query:
Internal Exception: java.sql.SQLException: Missing IN or OUT parameter at index:: 1
Error Code: 17041
Call: SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER, R.RQST_ID RQST_ID, R.TITLE TITLE, R.DESCRIPTION DESCRIPTION, DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID AND EMP.EMPL_ID IN :ids ORDER BY 1, 5 DESC, 2
Query: ReadAllQuery(name="requestByRequestor.getRequestsByRequesters" referenceClass=RequestByRequester sql="SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER, R.RQST_ID RQST_ID, R.TITLE TITLE, R.DESCRIPTION DESCRIPTION, DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID AND EMP.EMPL_ID IN :ids ORDER BY 1, 5 DESC, 2")
Exception when I use ?1 or (?) in the query :
Internal Exception: java.sql.SQLException: Invalid column type
Error Code: 17004
Call: SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER, R.RQST_ID RQST_ID, R.TITLE TITLE, R.DESCRIPTION DESCRIPTION, DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID AND EMP.EMPL_ID IN ? ORDER BY 1, 5 DESC, 2
bind => [[2192, 632]]
Query: ReadAllQuery(name="requestByRequestor.getRequestsByRequesters" referenceClass=RequestByRequester sql="SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER, R.RQST_ID RQST_ID, R.TITLE TITLE, R.DESCRIPTION DESCRIPTION, DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID AND EMP.EMPL_ID IN ? ORDER BY 1, 5 DESC, 2")
The issue (I think, because you did not include the definition of your named query), is that you are executing a native SQL query, and a List is not a valid SQL/JDBC parameter value.
EclipseLink support List parameters for JPQL queries, but not for native SQL queries.
You need to either use JPQL, or define each of the parameters in your SQL
i.e.
EMP.EMPL_ID IN (:id1, :id2, :id3)
.setParameter("id1", idList.get(0));
.setParameter("id2", idList.get(1));
I think the problem is here
AND EMP.EMPL_ID IN (?)
To indicate positional parameters, you need to suffix the questionmark with the number.
AND EMP.EMPL_ID IN (?1)
Alternately, you can do
AND EMP.EMPL_ID IN (:empIds)
and then call your query like so
List<RequestByRequester> resultList = getEm().createNamedQuery(
"requestByRequestor.getRequestsByRequesters", RequestByRequester.class)
.setParameter("empIds", idList)
.getResultList();
In your code you are mapping emp.getId() to String
List<String> idList = new ArrayList<String>();
for(Employee emp : employeeList) {
idList.add(emp.getId().toString());
}
But I bet the type for this column EMP.EMPL_ID is Numeric or some such thing. When you perform
.setParameter("empIds", idList)
JPA will be converting that to a string value with quotes and escape chars etc. hence:
java.sql.SQLException: Invalid column type
try mapping to List<Long> or some other numeric type.
Query:
List<RequestByRequester> resultList = getEm().createNamedQuery(
"requestByRequestor.getRequestsByRequesters", RequestByRequester.class)
.setParameter("ids", idList)
.getResultList();
NamedQuery WHERE part:
WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID
AND EMP.EMPL_ID IN :ids
Notice the :ids is without brackets. This should work.

Categories