EntityManager.getResultList() does not return the expected result - sql

select a.AssignAccOwner,a.AssignBillRate,a.AssignPerdiem from orion_db.assignment as a where a.AssignmentId=25
I am able to execute the above query successfully . But when I try to execute the same query programatically using entityManager.createnativeQuery I am getting the resultList as 0
Below is the code
buff.append("select a.AssignAccOwner,a.AssignBillRate,a.AssignPerdiem from orion_db.assignment as a where a.AssignmentId=25");
Query q2 = entityManager.createNativeQuery(buff.toString());
resultList = q2.getResultList();
System.out.println("Geting the resultList in dao layer " + q2.getResultList().size());
System.out.println("Geting the result in dao layer " + resultList.size());
This is the result which I get in the log
Geting the resultList in dao layer 0
Geting the result in dao layer 0
Below is the assignment.java entity class
/**
* Assignment generated by hbm2java
*/
#Entity
#Table(name = "assignment")
public class Assignment implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer assignmentId;
private String assignAccOwner;
private BigDecimal assignBillRate;
private String assignPerdiem;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "AssignmentId", unique = true, nullable = false)
public Integer getAssignmentId() {
return this.assignmentId;
}
public void setAssignmentId(Integer assignmentId) {
this.assignmentId = assignmentId;
}
#Column(name = "AssignBillRate", precision = 10)
public BigDecimal getAssignBillRate() {
return this.assignBillRate;
}
public void setAssignBillRate(BigDecimal assignBillRate) {
this.assignBillRate = assignBillRate;
}
#Column(name = "AssignPerdiem", length = 30)
public String getAssignPerdiem() {
return this.assignPerdiem;
}
public void setAssignPerdiem(String assignPerdiem) {
this.assignPerdiem = assignPerdiem;
}
#Column(name = "AssignAccOwner", length = 100)
public String getAssignAccOwner() {
return this.assignAccOwner;
}
public void setAssignAccOwner(String assignAccOwner) {
this.assignAccOwner = assignAccOwner;
}
}

It was not the code issue , I was not connected to the local database and hence I was not getting the expected result..

Related

Hibernate QueryException Named parameter not bound error

I keep getting the error org.hibernate.QueryException: Named parameter not bound : item when I start my transaction in JPA using EntityManager createNativeQuery. I have my code below utilizing the entity manager, along with my embeddedID class (for the composite key) and my persistence entity bean. Is there a problem in my query syntax? I am not sure as I've tried multiple ways of formatting the sql (coming from a properties file where there resides multiple sqls used throughout the project, and attempting to persist data to an oracle db). I am not sure why I keep falling on this error. I want to persist this data to my oracle database but this error keeps preventing that.
Query from query.properties file:
insertPromoData =INSERT INTO TEST.U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY, U_TIMESTAMP) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity, SYSDATE)
Embeddedable Class for establishing composite primary key on the target table:
#Embeddable
public class PromoID implements Serializable {
#Column(name = "ITEM")
private String item;
#Column(name = "LOC")
private String loc;
#Column(name = "WK_START")
private Date weekStart;
#Column(name = "TYPE")
private int type;
#Column(name = "FCSTID")
private String forecastId;
#Column(name = "U_TIMESTAMP")
private Timestamp insertTS;
public PromoID() {
}
public PromoID (String item, String loc, Date weekStart, int type, String forecastId, Timestamp insertTS) {
this.item = item;
this.loc = loc;
this.weekStart = weekStart;
this.type = type;
this.forecastId = forecastId;
this.insertTS = insertTS;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Date getWeekStart() {
return weekStart;
}
public void setWeekStart(Date weekStart) {
this.weekStart = weekStart;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getForecastId() {
return forecastId;
}
public void setForecastId(String forecastId) {
this.forecastId = forecastId;
}
public Timestamp getInsertTS() {
return insertTS;
}
public void setInsertTS(Timestamp insertTS) {
this.insertTS = insertTS;
}
//removed hashcode and equals methods for simplicity
Persistence Entity Bean:
#Entity
#Table(name = "U_USER_PROMO")
public class InsertPromoData {
#EmbeddedId
private PromoID id;
/*#Column(name="BATCH_ID")
String batchID;*/
#Column(name="ITEM")
String item;
#Column(name="LOC")
String loc;
#Column(name="WK_START")
String weekStart;
#Column(name="TYPE")
String type;
#Column(name="FCSTID")
String forecastId;
#Column(name="U_TIMESTAMP")
String insertTS;
#Column(name="NUMBER_OF_WEEKS")
String numberOfWeeks;
#Column(name="QTY")
String qty;
#Id
#AttributeOverrides(
{
#AttributeOverride(name = "item",column = #Column(name="ITEM")),
#AttributeOverride(name = "loc", column = #Column(name="LOC")),
#AttributeOverride(name = "weekStart", column = #Column(name="WK_START")),
#AttributeOverride(name = "type", column = #Column(name="TYPE")),
#AttributeOverride(name = "forecastId", column = #Column(name="FCSTID"))
}
)
public PromoID getId() {
return id;
}
public void setId(PromoID id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getWeekStart() {
return weekStart;
}
public void setWeekStart(String weekStart) {
this.weekStart = weekStart;
}
public String getNumberOfWeeks() {
return numberOfWeeks;
}
public void setNumberOfWeeks(String numberOfWeeks) {
this.numberOfWeeks = numberOfWeeks;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getForecastId() {
return forecastId;
}
public void setForecastId(String forecastId) {
this.forecastId = forecastId;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getInsertTS() {
return insertTS;
}
public void setInsertTS(String insertTS) {
this.insertTS = insertTS;
}
}
My dao OracleImpl.java using EntityManager for persisting:
public void insertPromoData(List<InsertPromoData> insertData) {
logger.debug("Execution of method insertPromoData in Dao started");
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
System.out.println("Beginning transaction for insertPromoData");
Query query = em.createNativeQuery(env.getProperty("insertPromoData"));
for (InsertPromoData promoData : insertData) {
query.setParameter("item", promoData.getItem());
query.setParameter("location", promoData.getLoc());
query.setParameter("wkStart", promoData.getWeekStart());
query.setParameter("numberOfWeeks", promoData.getNumberOfWeeks());
query.setParameter("type", promoData.getType());
query.setParameter("fcstId", promoData.getForecastId());
query.setParameter("quantity", Double.valueOf(promoData.getQty()));
}
query.executeUpdate();
System.out.println("Data for promo persisted");
em.getTransaction().commit();
}
catch(Exception e) {
logger.error("Exception in beginning transaction");
e.printStackTrace();
}
finally {
em.clear();
em.close();
}
logger.debug("Execution of method insertPromoData in Dao ended");
}
PromoValidator.java class:
List <InsertPromoData> insertPromos = new ArrayList<>();
promo.forEach(record -> {
if (record.getErrorList().size() == 0) {
rowsSuccessful++;
record.setItem(record.getItem());
record.setLoc(record.getLoc());
record.setNumber_Of_Weeks(record.getNumber_Of_Weeks());
record.setForecast_ID(record.getForecast_ID());
record.setType(record.getType());
record.setUnits(record.getUnits());
record.setWeek_Start_Date(record.getWeek_Start_Date());
insertPromos = (List<InsertPromoData>) new InsertPromoData();
for (InsertPromoData insertPromoData : insertPromos) {
insertPromoData.setItem(record.getItem());
insertPromoData.setLoc(record.getLoc());
insertPromoData.setWeekStart(LocalDate.parse(record.getWeek_Start_Date()));
insertPromoData.setNumberOfWeeks(Integer.parseInt(record.getNumber_Of_Weeks()));
insertPromoData.setType(Integer.parseInt(record.getType()));
insertPromoData.setForecastId(record.getForecast_ID());
insertPromoData.setQty(Double.parseDouble(record.getUnits()));
}
} else {
if (rowsFailure == 0) {
Util.writeHeaderToFile(templateCd, errorFile);
}
rowsFailure++;
Util.writeErrorToFile(templateCd, errorFile, record, record.getErrorList());
}
});
errorFile.close();
successFile.close();
OracleImpl.insertPromoData(insertPromos);
One of the reason this can happen is when insertData List you are passing is empty.
If I use below code ( please note that I have removed few columns to simplify it on my test environment with H2 database) - I get the error you described if empty list is passed and that's because there is indeed nothing to bind for the name parameter as the loop is not executed.
try {
em.getTransaction().begin();
System.out.println("Beginning transaction for insertPromoData");
Query query = em.createNativeQuery(
"INSERT INTO U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity)");
for (InsertPromoData promoData : insertData) {
query.setParameter("item", promoData.getId().getItem());
query.setParameter("location", promoData.getId().getLoc());
query.setParameter("wkStart", promoData.getId().getWeekStart());
query.setParameter("numberOfWeeks", promoData.getNumberOfWeeks());
query.setParameter("type", promoData.getId().getType());
query.setParameter("fcstId", promoData.getId().getForecastId());
query.setParameter("quantity", Double.valueOf(promoData.getQty()));
}
query.executeUpdate();
System.out.println("Data for promo persisted");
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
em.clear();
em.close();
}
The error I get is
org.hibernate.QueryException: Named parameter not bound : item
at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:210)
at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1425)
at org.hibernate.query.internal.NativeQueryImpl.beforeQuery(NativeQueryImpl.java:249)
at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1610)
at com.danielme.blog.nativesql.dao.UserDao.insertPromoData(UserDao.java:99)
However - if I pass non-empty list - this works as expected
SQLCustomQuery:72 - Starting processing of sql query [INSERT INTO U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity)]
AbstractFlushingEventListener:74 - Flushing session
I also encountered same problem. I noticed that I was defining the parameter in the query but I was not setting its value in:
query.setParameter(parameterToBeSet,parameterValue)
For example,
String hql = "FROM COLLEGE FETCH ALL PROPERTIES WHERE studentId = :studentId AND departmentId = :departmentId AND studentName = :studentName";
DBConnectionManager.getInstance().invokeCallableOnSessionMasterDB(session -> {
Query<CollegeEntity> query = session.createQuery(hql);
query.setParameter("studentId", studentId);
query.setParameter("departmentId", departmentId);
values.addAll(query.list());
});
As you can see the student name value was not set. So, after adding:
query.setParameter("studentName", studentName);
It got solved.
GETRequest : localhost:8080/getbyCity/chennai,mumbai,kolkata -
error ---> when I send this request I got------->"Hibernate QueryException Named parameter not bound error".
Answer: when we send list of parameter we should mention the "/" at the End. ((( localhost:8080/getbyCity/chennai,mumbai,kolkata/ ))). Set the bound using "/".
In my case I have put same parameter name to the procedure as:
#Param("managementAccess") Boolean managementAccess,
#Param("managementAccess") String dealerCode,
#Param("managementAccess") String dealerName,
Here the parameter name is different but inside string the name is same.
Solution is:
#Param("managementAccess") Boolean managementAccess,
#Param("dealerCode") String dealerCode,
#Param("dealerName") String dealerName,

HQL left join with foreign key from the second table [duplicate]

I would like to ask how to change the OUTER from Informix to HQL query. Currently facing error with unexpected token:outer
SQL query:
select a.SC_OB_PROFILE_CODE, b.SC_ORIG_SF_GROUP_CODE, f.SC_ORIG_SAC,
f.SC_ORIG_FAC,b.SC_PROD_CONT_GROUP_CODE, d.SC_PROD_CONT_CODE, e.GP_CD, a.SC_ORIG_COUNTRY,
a.SC_DEST_COUNTRY, a.SC_DEST_SAC, a.SC_DEST_FAC, a.SC_SEND_DOW,
a.SC_OB_SORT_CODE, a.ORIG_OB_SORT_CODE, a.TARGET_OB_SORT_CODE, a.SC_TIMESTAMP
from SC_OB_TEMP_AUDIT2 a, SC_OB_ALLOCATION b, outer SC_FAC_GROUP f,
outer (SC_OB_PROD_GROUP d, GBL_PRODUCT e)
where a.SC_ORIG_COUNTRY = 'MY'
and a.EXPORT_FLAG = 'N'
and a.SC_OB_PROFILE_CODE = b.SC_OB_PROFILE_CODE
and a.SC_ORIG_COUNTRY = b.SC_ORIG_COUNTRY
and f.SC_ORIG_COUNTRY = b.SC_ORIG_COUNTRY
and b.SC_ORIG_SF_GROUP_CODE = f.SC_FAC_GROUP_CODE
and d.SC_ORIG_COUNTRY = b.SC_ORIG_COUNTRY
and b.SC_PROD_CONT_GROUP_CODE = d.SC_PROD_GROUP_CODE
and e.GP_CNT_CD = d.SC_PROD_CONT_CODE
order by a.SC_TIMESTAMP, a.SC_OB_PROFILE_CODE, a.SC_DEST_COUNTRY
HQL query:
#SuppressWarnings("unchecked")
public List<LoginCountryEBean> getExportDetails(String country){
List<LoginCountryEBean> expDel = null;
Query q= em1.createQuery("select a.obProfileCode, b.sfGroupCode, f.orgSac," +
"f.sc_orig_fac,b.contGroupCode, d.prodContCode, e.gpCd, a.origCountry," +
"a.destCountry, a.destSac, a.destFac, a.sendDow, a.obSortCode, " +
"a.origObSortCode, a.targetObSortCode, a.timeStamp from AuditBean a, " +
"AllocationEBean b, **outer** FacGroupEBean f,**outer**(ProdGroupEBean d, glbProductEBean e)" +
"where a.origCountry :country and a.exportFlag = 'N' " +
"and a.obProfileCode = b.profileCode" +
"and a.origCountry = b.orgCountry" +
"and f.orgCountry = b.orgCountry" +
"and b.sfGroupCode = f.facGroupCode" +
"and d.orgCountry = b.orgCountry" +
"and b.contGroupCode = d.prodGroupCode" +
"and e.gpCntCd = d.prodContCode" +
"order by a.timeStamp, a.obProfileCode, a.destCountry");
q.setParameter("country", country);
expDel = q.getResultList();
return expDel;
//
AllocationEBean
package com.dhl.gls.persistence.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="SC_OB_ALLOCATION")
public class AllocationEBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="sc_orig_country")
private String orgCountry;
#Id
#Column(name="sc_orig_sf_group_code")
private String sfGroupCode;
#Id
#Column(name="sc_prod_cont_group_code")
private String contGroupCode;
#Id
#Column(name="sc_ob_profile_code")
private String profileCode;
public String getOrgCountry() {
return orgCountry;
}
public void setOrgCountry(String orgCountry) {
this.orgCountry = orgCountry;
}
public String getSfGroupCode() {
return sfGroupCode;
}
public void setSfGroupCode(String sfGroupCode) {
this.sfGroupCode = sfGroupCode;
}
public String getContGroupCode() {
return contGroupCode;
}
public void setContGroupCode(String contGroupCode) {
this.contGroupCode = contGroupCode;
}
public String getProfileCode() {
return profileCode;
}
public void setProfileCode(String profileCode) {
this.profileCode = profileCode;
}
}
//
AuditEBean
package com.dhl.gls.persistence.bean;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="sc_ob_temp_audit2")
public class AuditBean implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="audit_Id")
private long auditId;
#Column(name="sc_ob_profile_code")
private String obProfileCode = null;
#Column(name="sc_orig_country")
private String origCountry = null;
#Column(name="sc_dest_country")
private String destCountry = null;
#Column(name="sc_dest_sac")
private String destSac = null;
#Column(name="sc_dest_fac")
private String destFac = null;
#Column(name="sc_send_dow")
private String sendDow = null;
#Column(name="sc_ob_sort_code")
private String obSortCode = null;
#Column(name="orig_ob_sort_code")
private String origObSortCode = null;
#Column(name="target_ob_sort_code")
private String targetObSortCode = null;
#Column(name="usr_id")
private String userId = null;
#Column(name="sc_timestamp")
private Date timeStamp = null;
#Column(name="export_flag")
private String exportFlag = null;
public String getObProfileCode() {
return obProfileCode;
}
public String getOrigCountry() {
return origCountry;
}
public String getDestCountry() {
return destCountry;
}
public String getDestSac() {
return destSac;
}
public String getDestFac() {
return destFac;
}
public String getSendDow() {
return sendDow;
}
public String getObSortCode() {
return obSortCode;
}
public String getOrigObSortCode() {
return origObSortCode;
}
public String getTargetObSortCode() {
return targetObSortCode;
}
public Date getTimeStamp() {
return timeStamp;
}
public String getExportFlag() {
return exportFlag;
}
public void setObProfileCode(String obProfileCode) {
this.obProfileCode = obProfileCode;
}
public void setOrigCountry(String origCountry) {
this.origCountry = origCountry;
}
public void setDestCountry(String destCountry) {
this.destCountry = destCountry;
}
public void setDestSac(String destSac) {
this.destSac = destSac;
}
public void setDestFac(String destFac) {
this.destFac = destFac;
}
public void setSendDow(String sendDow) {
this.sendDow = sendDow;
}
public void setObSortCode(String obSortCode) {
this.obSortCode = obSortCode;
}
public void setOrigObSortCode(String origObSortCode) {
this.origObSortCode = origObSortCode;
}
public void setTargetObSortCode(String targetObSortCode) {
this.targetObSortCode = targetObSortCode;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
public void setExportFlag(String exportFlag) {
this.exportFlag = exportFlag;
}
public long getAuditId() {
return auditId;
}
public void setAuditId(long auditId) {
this.auditId = auditId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
//
prodGroupEBean
package com.dhl.gls.persistence.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="SC_OB_PROD_GROUP")
public class ProdGroupEBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="sc_orig_country")
private String orgCountry;
#Id
#Column(name="sc_prod_cont_code")
private String prodContCode;
#Id
#Column(name="sc_prod_group_code")
private String prodGroupCode;
public String getOrgCountry() {
return orgCountry;
}
public void setOrgCountry(String orgCountry) {
this.orgCountry = orgCountry;
}
public String getProdContCode() {
return prodContCode;
}
public void setProdContCode(String prodContCode) {
this.prodContCode = prodContCode;
}
public String getProdGroupCode() {
return prodGroupCode;
}
public void setProdGroupCode(String prodGroupCode) {
this.prodGroupCode = prodGroupCode;
}
}
//
FacGroupEBean
package com.dhl.gls.persistence.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="SC_FAC_GROUP")
public class FacGroupEBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="sc_orig_country")
private String orgCountry;
#Id
#Column(name="sc_orig_sac")
private String orgSac;
#Id
#Column(name="sc_orig_fac")
private String orgFac;
#Id
#Column(name="sc_fac_group_code")
private String facGroupCode;
public String getOrgCountry() {
return orgCountry;
}
public void setOrgCountry(String orgCountry) {
this.orgCountry = orgCountry;
}
public String getOrgSac() {
return orgSac;
}
public void setOrgSac(String orgSac) {
this.orgSac = orgSac;
}
public String getOrgFac() {
return orgFac;
}
public void setOrgFac(String orgFac) {
this.orgFac = orgFac;
}
public String getFacGroupCode() {
return facGroupCode;
}
public void setFacGroupCode(String facGroupCode) {
this.facGroupCode = facGroupCode;
}
}
//
glsproductionEBean
package com.dhl.gls.persistence.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="GBL_PRODUCT")
public class glbProductEBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="gp_cd")
private String gpCd;
#Column(name="gp_cnt_cd")
private String gpCntCd;
#Column(name="gp_sort_cd")
private String gpSortCd;
#Column(name="gp_short_nm")
private String gp_short_nm;
#Column(name="hf_lk")
private Long hfkl;
#Column(name="pasdt_cd")
private String pasdtCd;
#Column(name="psd_cd")
private Short psdCd;
#Column(name="gp_geo_markt")
private String gpGeoMarkt;
#Column(name="gp_doc_ndoc_ind")
private String gpDocNdocInd;
public String getGpCd() {
return gpCd;
}
public void setGpCd(String gpCd) {
this.gpCd = gpCd;
}
public String getGpCntCd() {
return gpCntCd;
}
public void setGpCntCd(String gpCntCd) {
this.gpCntCd = gpCntCd;
}
public String getGpSortCd() {
return gpSortCd;
}
public void setGpSortCd(String gpSortCd) {
this.gpSortCd = gpSortCd;
}
public String getGp_short_nm() {
return gp_short_nm;
}
public void setGp_short_nm(String gp_short_nm) {
this.gp_short_nm = gp_short_nm;
}
public Long getHfkl() {
return hfkl;
}
public void setHfkl(Long hfkl) {
this.hfkl = hfkl;
}
public String getPasdtCd() {
return pasdtCd;
}
public void setPasdtCd(String pasdtCd) {
this.pasdtCd = pasdtCd;
}
public Short getPsdCd() {
return psdCd;
}
public void setPsdCd(Short psdCd) {
this.psdCd = psdCd;
}
public String getGpGeoMarkt() {
return gpGeoMarkt;
}
public void setGpGeoMarkt(String gpGeoMarkt) {
this.gpGeoMarkt = gpGeoMarkt;
}
public String getGpDocNdocInd() {
return gpDocNdocInd;
}
public void setGpDocNdocInd(String gpDocNdocInd) {
this.gpDocNdocInd = gpDocNdocInd;
}
}
The syntax to make a join is
select ... from Entity1 e1
[inner | left [outer]] join e1.entity2s e2
[inner | left [outer]] join e2.entity3s e3
...
Read the documentation
The trouble you're running into is that the (obsolescent) old-style Informix OUTER join notation is not understood by other systems (such as HQL). Here's a slightly simplified version of the original Informix query:
select a.*, b.*, d.*, e.*, f.*
from SC_OB_TEMP_AUDIT2 a,
SC_OB_ALLOCATION b,
outer SC_FAC_GROUP f,
outer (SC_OB_PROD_GROUP d, GBL_PRODUCT e)
where a.SC_ORIG_COUNTRY = 'MY'
and a.EXPORT_FLAG = 'N'
and a.SC_OB_PROFILE_CODE = b.SC_OB_PROFILE_CODE
and a.SC_ORIG_COUNTRY = b.SC_ORIG_COUNTRY
and f.SC_ORIG_COUNTRY = b.SC_ORIG_COUNTRY
and b.SC_ORIG_SF_GROUP_CODE = f.SC_FAC_GROUP_CODE
and d.SC_ORIG_COUNTRY = b.SC_ORIG_COUNTRY
and b.SC_PROD_CONT_GROUP_CODE = d.SC_PROD_GROUP_CODE
and e.GP_CNT_CD = d.SC_PROD_CONT_CODE
order by a.SC_TIMESTAMP, a.SC_OB_PROFILE_CODE, a.SC_DEST_COUNTRY;
Primarily, I've simplified the select-list by using a.* notation for selecting the columns from each aliased table name, and I've exposed the FROM clause contents a bit more clearly.
The tables (with aliases — but I'm going to pretend that the aliases are the table names) a and b are inner joined. That is outer joined to f; it is also independently outer joined to the result of d outer joined to e. To rewrite this so that HQL has a chance of understanding it, we're going to have to write something close to this:
SELECT a.*, b.*, d.*, ef.*
FROM sc_ob_temp_audit2 AS a
JOIN sc_ob_allocation AS b
ON a.sc_ob_profile_code = b.sc_ob_profile_code
AND a.sc_orig_country = b.sc_ob_orig_country
OUTER JOIN sc_fac_group AS f
ON b.sc_orig_country = f.sc_orig_country
AND b.sc_orig_sf_group_code = f.sc_fac_group_code
OUTER JOIN (SELECT e.*, f.*
FROM sc_ob_prod_group AS d
OUTER JOIN gbl_produce AS e
ON d.sc_prod_cont_code = e. gp_cnt_cd
) AS ef.*
ON b.sc_orig_country = ef.sc_orig_country
AND b.sc_prod_cont_group_code = ef.sc_prod_group_code
WHERE a.sc_orig_country = 'MY'
AND a.export_flag = 'N'
ORDER BY a.sc_timestamp, a.sc_ob_profile_code, a.sc_dest_country;
Apart from inverting the case of keywords vs database objects, this is a fairly direct translation of the original query. You will note that the outer joined sub-query is given the alias ef in this revision. This is necessary; the SQL standard mandates that such sub-queries are given an alias. You therefore may run into ambiguous column errors. You can probably fix those by by replacing the * notation in the sub-query with the exact set of column names you want to select. And, of course, you'll need to replace the * notation in the select-list with the set of columns that you want once more.

Android room compiler error when trying to return a list of own objects in the DAO: incompatible types: <null> cannot be converted to int

I am using room for database operations. I have a class TableQuestion which holds a string and a id and I have a class TableAnswer which holds a string, an id plus the id of the question where it is refering to. QuizTask brings together the Question with all its answers. The query getQuestionsWithAnswer should return a QuizTask which wraps the question with all its answers. The error metioned in the title happens in auto-generated code of room.
The relevant part of the interface:
#android.arch.persistence.room.Dao
public interface dbDao {
#Transaction
#Query("SELECT table_question.question, table_answer.answer FROM table_question, table_answer WHERE table_question.id = table_answer.id_question")
LiveData<List<QuizTask>> getQuestionsWithAnswers();
}
Class TableQuestion:
#Entity(foreignKeys = #ForeignKey(entity = TableQuestionnaire.class,
parentColumns = "id",
childColumns = "id_questionnaire",
onDelete = CASCADE),
tableName = "table_question")
public class TableQuestion {
#PrimaryKey
public final int id;
#NonNull
public String question;
#NonNull
public int id_questionnaire;
public String subject;
public String category;
public String sub_category;
#Ignore
public String questionnaire;
public TableQuestion(int id, #NonNull String question, int id_questionnaire, String subject, String category, String sub_category) {
this.id = id;
this.question = question;
this.id_questionnaire = id_questionnaire;
this.questionnaire = null;
this.subject = subject;
this.category = category;
this.sub_category = sub_category;
}
public void setQuestionnaire(String questionnaire){
this.questionnaire = questionnaire;
}
}
Class TableAnswer:
#Entity(foreignKeys = #ForeignKey(entity = TableQuestion.class,
parentColumns = "id",
childColumns = "id_question",
onDelete = CASCADE),
tableName = "table_answer")
public class TableAnswer {
#PrimaryKey
public final int id;
#NonNull
public String answer;
#NonNull
public final int id_question;
public boolean rightAnswer;
public TableAnswer(int id, String answer, int id_question, boolean rightAnswer) {
this.id = id;
this.answer = answer;
this.id_question = id_question;
this.rightAnswer = rightAnswer;
}
}
Class QuizTask:
public class QuizTask {
#Embedded
private TableQuestion question;
#Relation(parentColumn = "id", entityColumn = "id_question")
private List<TableAnswer> answers;
public void setQuestion(TableQuestion question){ this.question = question; }
public TableQuestion getQuestion(){
return question;
}
public void setAnswers(List<TableAnswer> answers) { this.answers = answers; }
public List<TableAnswer> getAnswers() {
return answers;
}
}
AndroidStudio doesn't show any error upon compilation. When room auto-generates the code for getQuestionWithAnswers it shows a compiler error "incompatible types: cannot be converted to int". In the auto-generated dbDao_Impl.java is a row where a TableQuestion object is tried to create but with null for the id parameter. That's where the error occurs. What do I have to change?
I found the issue:
#Query("SELECT table_question.question, table_answer.answer FROM table_question, table_answer WHERE table_question.id = table_answer.id_question")
There is no id selected but used later on. That's why room tries to create objects with Id = null which is not possible. So simply change to:
#Query("SELECT * FROM table_question, table_answer WHERE table_question.id = table_answer.id_question")

SQLGrammarException with native Query in spring boot

I tried to run a GettMapping with Postman. But it's not working and I am getting the error:
Status 500 error. SQLGrammarException: could not extract ResultSet
#GetMapping("/clients/month/{month}")
public Meter getAllMeterByMonth(#PathVariable (value = "month") String month) {
return meterRepository.findByMonth(month);
}
Repository:
public interface MeterRepository extends JpaRepository<Meter, Long> {
Meter findByClientId(Long clientId);
#Query(value = "select * from meter where month = :month", nativeQuery = true)
Meter findByMonth(#Param("month")String month);
}
Client Entity:
#Entity
#Table(name = "clients")
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(max = 100)
private String name;
Meter entity:
#Entity
#Table(name = "meters")
public class Meter{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(name="year")
private int year;
#NotNull
#Column(name="month")
private String month;
#NotNull
private int value;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "client_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
#JsonIdentityReference(alwaysAsId=true)
#JsonProperty("client_id")
private Client client;
Do you have any ideas about my issue ?
You are facing this error just because of a simple typo. Replace meter with meters in the query mentioned in MeterRepository.java.
Something like this:
package com.stackoverflow;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface MeterRepository extends JpaRepository<Meter, Long> {
#Query(value = "select * from meters where month = :month", nativeQuery = true)
Meter findByMonth(#Param("month")String month);
}

Entity not posting to restful service

I'm having trouble posting a request to a restfull service.
It looks like my Entity is not getting converted into json correctly.
I get a 400 Bad request response.
I suspect it's the List of DateTimeRange objects causing the issue - as I have a very similar request that works but all the pojos properties are Strings.
Do I need to annotate my Entity to enable marshalling to/from json for Lists and my custom DateTimeRange?
String actionUrl = buildUrl( myResftullUrlTest );
Client client = ClientBuilder.newClient().register( JacksonJsonProvider.class );
Builder target = client.target( actionUrl ).request();
CreateWebinarRequest createWebinarRequest = new CreateWebinarRequest();
createWebinarRequest.setDescription("Test1 desc");
createWebinarRequest.setSubject("Test1 subject")
createWebinarRequest.setTimeZone("Europe/Dublin")
List<DateTimeRange> dateTimeRangeParam = new ArrayList<DateTimeRange>();
DateTimeRange dateTimeRange = new DateTimeRange();
dateTimeRange.setStartTime( "2016-11-03T08:34:12" );
dateTimeRange.setEndTime( "2016-11-03T09:34:12" );
dateTimeRangeParam.add( dateTimeRange );
createWebinarRequest.setTimes( dateTimeRangeParam );
Response response = null;
switch ( goToTrainingRequestData.getRequestType() ) {
case HTTP_POST :
response = target.buildPost( Entity.json(createWebinarRequest) ).invoke();
...
}
}
CreateWebinarRequest:
public class CreateWebinarRequest implements Serializable {
private String subject = null;
private String description = null;
private List<DateTimeRange> times = new ArrayList<DateTimeRange>();
private String timeZone = null;
public String getSubject() {
return subject;
}
public void setSubject( String subject ) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription( String description ) {
this.description = description;
}
public List<DateTimeRange> getTimes() {
return times;
}
public void setTimes( List<DateTimeRange> times ) {
this.times = times;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone( String timeZone ) {
this.timeZone = timeZone;
}
}
DateTimeRange:
public class DateTimeRange {
private String startTime = null;
private String endTime = null;
public String getStartTime() {
return startTime;
}
public void setStartTime( String startTime ) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime( String endTime ) {
this.endTime = endTime;
}
}
Problem solved guys and gals!
Nothing wrong with any data marshalling, I got the detailed response from server with:
String error = response.readEntity( String.class );
And it was a boo boo on my behalf!
{"errorCode":"RequestValidationError","description":"Request contains invalid parameters. See validationErrorCodes for specific errors.","Details":"times cannot be in past","incident":"6100682426566883853","validationErrorCodes":[{"code":"requestStartTimeInPast","description":"times cannot be in past"}]}