What does "my_something" means in oracle sql query? - java

I have some Java code that runs an SQL query like this:
SELECT DISTINCT ven.enterprise_network_id, st.*
FROM studies st
inner join v_enterprise_network_members ven on st.ib_id = my_ib_id
WHERE ven.ib_id=:IB_ID
AND (st.myvrn_expiration_date IS NULL OR st.myvrn_expiration_Date >= sysdate)
ORDER BY st.study_date DESC
I understand everything except I don't understand what st.ib_id=my_ib_id. What does it mean? This is the whole method just in case if it helps:
public List<Study> searchRepository(StudySearchCriteria criteria, boolean isEnterpriseNetwork,
boolean isExactNameMatch) {
String selectForNone = null;
String studyStatus = null;
studyStatus = verifyStudyStatus(criteria, studyStatus, isEnterpriseNetwork);
if (criteria.contains(SearchField.STUDY_STATUS) && StringUtils.isBlank(studyStatus)) {
return new ArrayList<>();
}
if (StringUtils.isNotBlank(studyStatus) && studyStatus.contains(StudyPacsState.State.NONE.toString())) {
selectForNone = "DISTINCT {st.*}, st.study_date as stdate FROM studies st";
}
StringBuffer select = new StringBuffer(512);
StringBuffer where = new StringBuffer(512);
StringBuffer orderBy = new StringBuffer(selectForNone != null ? "" : " ORDER BY st.study_date DESC ");
select.append("SELECT ");
if (criteria.containsWildcard()) {
select.append(queryHint);
}
if (!isEnterpriseNetwork) {
select.append(selectForNone != null ? selectForNone : "DISTINCT {st.*} FROM studies st");
where.append(" WHERE st.ib_id=:IB_ID AND ").append(myVrnSql);
}
else {
///////////////////////////////////// HERE IS WHERE my_ib_id is
select.append("DISTINCT ven.enterprise_network_id, {st.*} FROM studies st")
.append(" inner join v_enterprise_network_members ven on st.ib_id=my_ib_id ");
/////////////////////////////////////
where.append(" WHERE ven.ib_id=:IB_ID AND ").append(myVrnSql);
}
StringBuilder queryForNone = selectForNone != null ? new StringBuilder(" UNION ") : new StringBuilder(" ");
createStudyStatusQuery(criteria, isExactNameMatch, studyStatus, where, queryForNone, false);
buildStudyQuery(criteria, select, where, orderBy, isEnterpriseNetwork, isExactNameMatch, true, false);
if (criteria.contains(SearchField.STUDY_STATUS)) {
select.append(" , smr_study_pacs_state sps ");
}
SQLQuery sq = null;
Query hq = null;
if (isEnterpriseNetwork) {
sq = getSession().createSQLQuery(select.toString() + where.toString());
sq.addEntity("st", Study.class).addScalar("enterprise_network_id", StandardBasicTypes.LONG)
.setCacheable(false).setCacheRegion("vrnstudysearch");
}
else {
sq = getSession().createSQLQuery(select.toString() + where.toString() + queryForNone.toString());
sq.addEntity("st", Study.class).setCacheable(false).setCacheRegion("vrnstudysearch");
if (selectForNone != null) {
sq.addScalar("stdate", StandardBasicTypes.TIMESTAMP);
}
}
hq = sq;
hq.setLong(SearchField.IB_ID.toString(), (Long) criteria.get(SearchField.IB_ID));
supplyParameters(criteria, hq, isExactNameMatch);
logger.info("Query searchRepository {}", hq.getQueryString());
List<Study> result = null;
if (!isEnterpriseNetwork) {
if (selectForNone != null) {
List<?> returned = hq.list();
if (returned != null) {
result = new ArrayList<Study>();
for (Object n : returned) {
Object[] tuple = (Object[]) n;
Study st = (Study) tuple[0];
result.add(st);
}
}
}
else {
result = hq.list();
}
}
else {
List<?> returned = hq.list();
if (returned != null) {
result = new ArrayList<Study>();
for (Object n : returned) {
Object[] tuple = (Object[]) n;
Study st = (Study) tuple[0];
st.setEnterpriseNetworkId((Long) tuple[1]);
result.add(st);
}
}
}
logger.debug(" returned " + (result == null ? 0 : result.size()));
return result;
}

st.ib_id=my_ib_id is the join condition - it defines the relationship between the two tables you are joining in the query. Presumably, my_ib_id is a column in one of those tables.

Related

how to cast the result to String From Native Query in Java?

i have a query which will return single record with 2 columns from Table
i want to get the result to a List each element hold a column value , but i keep getting ClassCastExceptoion
this is the code :
public List<String> getStatus(Long requestId) {
List result = new ArrayList();
if (requestId != null)
{
StringBuilder querySBuilder = new StringBuilder();
querySBuilder.append(" select R.request_status_id , L.request_status_desc ");
querySBuilder.append(" from Table1 R join Table2 L ");
querySBuilder.append(" on R.request_status_id = L.REQUEST_STATUS_Id ");
querySBuilder.append(" where R.REQUEST_ID = " + requestId);
System.out.print(querySBuilder.toString());
List resultList =
em.createNativeQuery(querySBuilder.toString()).getResultList();
Vector resultVec = (Vector)resultList.get(0);
int id = ((BigDecimal)resultVec.elementAt(0)).intValue();
String statusName = ((String)resultVec.elementAt(0));
System.out.println("id" + id);
System.out.println("name " + statusName);
result.add(id);
result.add(statusName);
if (resultVec == null || resultVec.isEmpty()) {
return new ArrayList<String>();
}
return result;
}
return null;
}
The pattern I would use would be to phrase the incoming native result set as a List<Object[]>, where each object array represents a single record:
Query q = em.createNativeQuery(querySBuilder.toString());
List<Object[]> result = q.getResultList();
for (Object[] row : result) {
int id = (Integer)row[0];
String statusName = (String)row[1];
// do something with the id and statusName from above
}
I think it is a typo.
String statusName = ((String)resultVec.elementAt(0));
The elementAt(1) should be used instead of elementAt(0).

Exporting data to PDF JAVA, Eclipse, Jasper

I tried to make an exporting data to PDF but when I try to export it, the pdf can't show up like "no data found"
this code on bean
public JasperPrint exportTo() {
if(this.listReportMaster == null || this.listReportMaster.isEmpty()){
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
return null;
}
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/PRPKReportPDF.jasper");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.listReportMaster);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(path, null, beanCollectionDataSource);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public void exportToPdf(ActionEvent actionEvent){
if(this.lazyMasterReportDataModel != null){
System.out.println("masuk exporttopdf");
String sql = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getSqlReportPrint();
List<Object> listObject = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getObjectSqlListReportPrint();
this.listReportMaster = reportMasterPRPKController.getPRPKForReport(sql, listObject);
JasperPrint jasperPrint = exportTo();
String fileName = "PRPKNew_Report".concat("_").concat(".pdf");
if(jasperPrint != null) reportMasterPRPKController.exportToPDF(fileName, jasperPrint);
else System.out.println("jasperprint null");
}else{
System.out.println("keluar exporttopdf");
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
}
}
every I try to export it, always show "no data found" which is the program run this code FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found"); and which meam the "this.lazyMasterReportDataModel" is null but when I check it again, there's nothing wrong on code, I don't know if it have a wrong code or deficiency code
this the lazy code
List<ReportMasterPRPK> listMasterPRPK = new ArrayList<>();
ReportMasterPRPKQuery reportMasterPRPKQuery = new ReportMasterPRPKQuery();
Page page = new Page();
String order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
String columname = "";
String sql = "";
List<Object> objectSqlList = new ArrayList<>();
String sqlReport = "";
String sqlReportPrint = "";
List<Object> objectSqlListReport = new ArrayList<>();
List<Object> objectSqlListReportPrint = new ArrayList<>();
String flag;
public LazyMasterReportDataModel() {
}
public LazyMasterReportDataModel(String flag) { //ini
this.flag = flag;
}
public LazyMasterReportDataModel(String sqlReport, List<Object> objectSqlListReport) {
this.sqlReport = sqlReport;
this.objectSqlListReport = objectSqlListReport;
}
#Override
public List<ReportMasterPRPK> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
page.setLimit(pageSize);
page.setOffset(first);
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList = new ArrayList<>();
//objectSqlList.clear();
}
if(flag != null){ //ini
if(flag.equals("no selected")){
sql = sql+" AND c.is_selected = 'n' ";
}
}
if (filters != null){
for(String key: filters.keySet()){
String filterColumnName = "";
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(key)) filterColumnName = field.getAnnotation(Column.class).value();
}
if(filters.get(key) instanceof String){
if("receivedDate".equals(key)){
if(((String)filters.get(key)).trim().length() > 20){
String startDate = "'" + filters.get(key).toString().substring(0, 10) + "'";
String endDate = "'" + filters.get(key).toString().substring(11, 21) + "'";
sql = sql + " AND " + filterColumnName + " BETWEEN " + startDate + " AND " + endDate+ " ";
}
}else{
if(((String) filters.get(key)).trim().length() > 0){
sql = sql+"AND "+filterColumnName+" ILIKE ? ";
String value = "%"+filters.get(key)+"%";
objectSqlList.add(value);
}
}
}else{
if(((String[]) filters.get(key)).length > 0){
sql = sql+" AND "+filterColumnName+" in ";
String value = "(";
for(String string : (String[]) filters.get(key)){
value = value+"'"+string+"',";
}
value = value.substring(0, value.length()-1)+") ";
sql = sql + value;
}
}
}
}
if(sortField != null){
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(sortField)) columname = field.getAnnotation(Column.class).value();
}
if(sortOrder.toString().equals("ASCENDING")) order = " ASC";
else order = " DESC";
sql = sql+" GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY "+columname+" "+order;
System.out.println("sql sort: "+sql+" : "+objectSqlList.size());
}else{
sql = sql + order;
}
sqlReportPrint = sql;
objectSqlListReportPrint = objectSqlList;
this.listMasterPRPK = reportMasterPRPKQuery.retrivePage(page, sql, objectSqlList.toArray());
int dataSize = reportMasterPRPKQuery.retrieveMaxRow(sql, objectSqlList.toArray());
this.setRowCount(dataSize);
//objectSqlList.clear();
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList.clear();
}
order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
return listMasterPRPK;
}
public List<ReportMasterPRPK> calculateRownum(List<ReportMasterPRPK> listMasterPRPK, int first){
int i = 1;
for (ReportMasterPRPK masterPRPK : listMasterPRPK) {
masterPRPK.setRownum(first + i);
i++;
}
return listMasterPRPK;
}
public String getSqlReportPrint() {
return sqlReportPrint;
}
public void setSqlReportPrint(String sqlReportPrint) {
this.sqlReportPrint = sqlReportPrint;
}
public List<Object> getObjectSqlListReportPrint() {
return objectSqlListReportPrint;
}
public void setObjectSqlListReportPrint(List<Object> objectSqlListReportPrint) {
this.objectSqlListReportPrint = objectSqlListReportPrint;
}
sorry before, if my english is to bad, but I hope you understand about what I mean...
thanks before...

how to check if your query is empty using java

I'm using a spring framework and the code I'm using won't work or check if the query is null, though I used a .isEmpty() method it doesn't mean that the query is empty. I wanted to make sure that my query is empty because a part of my code does invoke an id in which case I didn't even though its null so please help me T.T
public List<Object> searchEmployee(EmployeeSearchDto data) {
Session session = sessionFactory.openSession();
final String CRITERIA_EMPLOYEEID = "emp.employeeID =:id";
final String CRITERIA_EMPLOYEEID2 = "emp.employeeID LIKE:id";
final String CRITERIA_POSITION= "emp.positionID =:posID";
final String CRITERIA_DEPARTMENT="emp.departmentID =:deptID";
final String CRITERIA_WORKPLACE = "emp.workplaceID =:workID";
Boolean selected_dept = false;
Boolean selected_pos = false;
Boolean selected_work = false;
Boolean input_empID = false;
Boolean input_empName = false;
firstName = "";
middleName = "";
lastName = "";
completeName = "";
firstLastName = "";
List<String> criteria = new ArrayList<>();
List<Object> employees = null;
// checking the fields if all the fields is empty
try{
//one by one check the select field
String query = "Select"
+ " emp.employeeID,"
+"emp.firstName,"
+"emp.middleName,"
+"emp.lastName,"
+"pos.positionName,"
+"dept.deptName,"
+"work.workplaceName"
+"from Employee emp "
+ "INNER JOIN Department dept "
+ "ON emp.departmentID = dept.deptID "
+ "INNER JOIN Position pos "
+ "ON emp.positionID = pos.positionID "
+ "INNER JOIN Workplace work "
+ "ON emp.workplaceID = work.workplaceID ";
if(!data.isEmpty()) {
query = query.concat("WHERE ");
if(data.getEmployeeID()!="" && data.getEmployeeID()!=null) {
criteria.add(CRITERIA_EMPLOYEEID2);
System.out.println("Employee IDs");
input_empID = true;
}
if(data.getEmployeeName()!="" && data.getEmployeeName()!=null){
criteria.add(nameCriteriaHelper(data.getEmployeeName()));
System.out.println("Employee Name AKOOO");
input_empName = true;
}
if(data.getDepartmentID()!=0) {
criteria.add(CRITERIA_DEPARTMENT);
System.out.println("Dept ID ");
selected_dept = true;
}
if(data.getPositionID()!=0) {
criteria.add(CRITERIA_POSITION);
System.out.println("POS ID ");
selected_pos = true;
}
if(data.getWorkplaceID()!=0) {
criteria.add(CRITERIA_WORKPLACE);
selected_work = true;
}
query = query.concat(String.join(" OR ", criteria));
}
query = query.concat(" ORDER BY emp.joinDate DESC");
System.out.println("QUERY: " + query);
Query q = session.createQuery(query);
if(input_empID) {
q.setParameter("id", "%" + data.getEmployeeID() + "%");
}
if(input_empName) {
if(searchbyOne)
q.setParameter("inputName", "%" + data.getEmployeeName() + "%");
if(searchbyFandL)
q.setParameter("firstLastName", "%" +firstLastName+ "%");
if(searchbyCompName)
q.setParameter("completeName", "%" +completeName+ "%");
}
if(selected_dept) {
q.setParameter("deptID", data.getDepartmentID());
}
if(selected_pos) {
q.setParameter("posID", data.getPositionID());
}
if(selected_work) {
q.setParameter("workID", data.getWorkplaceID());
}
employees = (List<Object>) q.list();
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
return employees;
}
public String nameCriteriaHelper(String name) {
searchbyOne = false;
searchbyFandL = false;
searchbyCompName = false;
final String noOfTokens_1 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :inputName";
final String noOfTokens_2 = "(CONCAT(emp.lastName, ' ', emp.firstName) LIKE :firstLastName "
+ "OR CONCAT(emp.firstName, ' ', emp.lastName) LIKE :firstLastName)";
final String noOfTokens_3 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :completeName";
StringTokenizer stringTokenizer = new StringTokenizer(name);
int no_of_tokens = stringTokenizer.countTokens();
switch(no_of_tokens) {
case 1: searchbyOne = true;
return noOfTokens_1;
case 2: firstName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
firstLastName = lastName + " " + firstName;
searchbyFandL = true;
return noOfTokens_2;
default: int counter = 0;
while( counter < (no_of_tokens - 2)) {
firstName = firstName.concat(stringTokenizer.nextToken() + " ");
counter++;
}
firstName = stringTokenizer.nextToken();
middleName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
completeName = lastName + " " + firstName + " " + middleName;
searchbyCompName = true;
return noOfTokens_3;
}
You're using wrong order and wrong function to compare string:
Replace:
data.getEmployeeID()!="" && data.getEmployeeID()!=null
With
data.getEmployeeID() != null && !data.getEmployeeID().equals("")
Comparing string must use equals(). And check for null should be done first, before accessing the equals method
You should correct other conditions as above too.
Actually, the logic that Mr. Nguyễn provided here is faulty. An object or variable cannot both be null and initialized to a default value (such as foo == "") at the same time.
At the time of the logic check, if the String is in fact null, the second half of the logic statement will engage, checking to see if the String is equal to "", which will throw a null pointer exception. Instead of checking for both at the same time, check for one and then check for the other like so:
//since two logic checks are being performed,
//it is advantageous to put the data from the query
//into memory so you don't have to get the
//same result twice
String foo = data.getEmployeeID();
if (foo != null)
{
if (!(foo.equals("")))
{
//the result is neither null or empty
}
else
{
//the result is not null but it is empty
}
}
else
{
//the result is null
}

Standard query JPA-CriteriaBuilder eclipseLink optimization

I'm developing a standard JPA criteriabuilder query with eclipse link, but I don't know how to optimize, when path navigation is more than two objects. For example if my class is called Car, Car.objectA.objectB.objectC..
CriteriaBuilder duplicates joins' table
This is my query code:
public List<T> getOrderedByFieldsValues(String sortField, SortOrder sortOrder, Map<String, Object> fieldValues) {
//#formatter:off
List<T> retorno = new ArrayList<T>();
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(getEntityClass());
Root<T> from = criteriaQuery.from(getEntityClass());
Predicate fullPredicate = null;
if (!fieldValues.isEmpty()) {
for (String fieldName : fieldValues.keySet()) {
if (!fieldName.contains(".")) {
if(predicateCompleto == null){
predicateCompleto = criteriaBuilder.equal(from.get(fieldName), fieldValues.get(fieldName));
}else{
predicateCompleto = criteriaBuilder.and(predicateCompleto,criteriaBuilder.equal(from.get(fieldName), fieldValues.get(fieldName)));
}
} else {
String[] campos = fieldName.split("\\.");
if (campos.length > 0) {// #formatter:off
if (campos.length <= 2) {
Join<T, T> p = from.join(campos[0]);
if(fullPredicate == null){
fullPredicate = criteriaBuilder.equal(p.get(campos[1]), fieldValues.get(fieldName));
}else{
fullPredicate = criteriaBuilder.and(fullPredicate , criteriaBuilder.equal(p.get(campos[1]), fieldValues.get(fieldName)));
}
} else {
//GENERATE DUPLICATE JOIN!!
Join<T, T>[]x = new Join[10];
//More than 10 joins is a party
for (int i = 0; i < campos.length; i++) {
if(!(i == (campos.length-1))){
if(i==0){
String valor = campos[i];
x[i] = from.join(valor);
}else{
if(i == 1){
x[i] = x[0].join(campos[i]);
}else{
//añadimos a la join anterior
x[i-1] = x[i-1].join(campos[i]);
}
}
}else{
if(fullPredicate == null){
fullPredicate = criteriaBuilder.equal(x[i-1].get(campos[i]), fieldValues.get(fieldName));
}else{
fullPredicate = criteriaBuilder.and(fullPredicate , criteriaBuilder.equal(x[i-1].get(campos[i]), fieldValues.get(fieldName)));
}
}
}
}
}
}
}
// WHERE
criteriaQuery.where(predicateCompleto);
}
if (sortField != null) {
String[] fields = sortField.split("\\.");
if (fields.length > 0) {
Path<Object> path = from.get(fields[0]);
for (int i = 1; i < fields.length; i++) {
path = path.get(fields[i]);
}
if (sortOrder == SortOrder.ASCENDING) {
criteriaQuery.orderBy(new Order[] { criteriaBuilder.asc(path) });
} else if (sortOrder == SortOrder.DESCENDING) {
criteriaQuery.orderBy(new Order[] { criteriaBuilder.desc(path) });
}
}
}
TypedQuery<T> typedQuery = getEntityManager().createQuery(criteriaQuery);
retorno = typedQuery.getResultList();
if(LOGGER.isDebugEnabled()){
LOGGER.info("QUERY - QUERY: " + typedQuery.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString());
}
return retorno;
}
With these parameters generate diferents alias from the same table..
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("label.labelId", labelId);
params.put("collection.collectionId", collectionId);
params.put("label.format.formatId", 1L);//3 objects path
params.put("label.kindOfLabel.tipoLabelId", 1L);//3 path
Resultant SQL QUERY:
SELECT t1.LABEL_COLECCTIONS_ID,
t1.ACTIVE,
t1.COMMENTS,
t1.CREATED_BY,
t1.CREATION_DATE,
t1.FILE_SUPPLIER,
t1.FILE_SUPPLIER_CONTENT_TYPE,
t1.LAST_UPDATE_DATE,
t1.LAST_UPDATED_BY,
t1.REVISION,
t1.SAMPLE,
t1.COLLECTION_ID,
t1.LABEL_ID,
t1.RELATED_LABEL_COLLECTION_ID,
t1.RELATED_SEASON_ID
FROM BET_LABELS t6,
BET_COLLECTION t5,
BET_FORMATO t4,
BET_LABELS t3,
BET_TIPO_LABEL t2,
BET_LABEL_COLLECTIONS t1,
BET_LABELS t0
WHERE (((((t0.TIPO_LABEL_ID = ?)
AND (t1.COLLECTION_ID = ?))
AND (t1.LABEL_ID = ?))
AND (t3.FORMATO_ID = ?))
AND ((((((t0.LABEL_ID = t1.LABEL_ID)
AND (t3.LABEL_ID = t1.LABEL_ID))
AND (t2.TIPO_LABEL_ID = t0.TIPO_LABEL_ID))
AND (t4.FORMATO_ID = t3.FORMATO_ID))
AND (t5.COLLECTION_ID = t1.COLLECTION_ID))
AND (t6.LABEL_ID = t1.LABEL_ID)))
I working on a solution but maybe some guy find here an interesting problem, any clue will be grateful.
ty.

code part I do not understand

I don't understand why in this code, it's do that:
query.setString("idFamilleDeProduit", String.valueOf(familleDeProduits.getFamilleDeProduitsGenerique().getId()));
When I looked my table in my database, id column is integer.
it's PostgreSql-9.4.1207
my function:
public List<ContratMdd> recherchePourDuplication(String typeAccord, FamilleDeProduitsNomenclature familleDeProduits, SocieteInterne societeInterne, SocieteExterne societeExterne, String anneeAccord) throws PersistenceException {
List<ContratMdd> listContratMdd = new ArrayList<ContratMdd>();
String requete = "";
if (!"".equals(anneeAccord)){
requete += " anneeAccord = :anneeAccord";
}
if (!"".equals(typeAccord) && ! "".equals(requete)){
requete += " AND";
}
if (!"".equals(typeAccord)){
requete += " type = :type";
}
boolean existFamille = false;
requete += (familleDeProduits != null && familleDeProduits.getFamilleDeProduitsGenerique() != null) ? " AND " : "";
if(familleDeProduits != null && familleDeProduits.getFamilleDeProduitsGenerique() != null){
existFamille = true;
requete += " estAppliqueSur.familleDeProduitsGenerique IS NOT NULL AND estAppliqueSur.familleDeProduitsGenerique.id = :idFamilleDeProduit";
}
boolean existSocieteInterne = false;
boolean existSocieteExterne = false;
requete += (societeInterne != null) ? " AND " : "";
if(societeInterne != null){
existSocieteInterne = true;
String table = societeInterne instanceof Master ? "MasterImpl" : "AdherentImpl";
requete += " contractantInterne.id = :idsocieteInterne AND contractantInterne IN (FROM "+table+") ";
}
requete += (societeExterne != null) ? " AND " : "";
if(societeExterne!=null){
existSocieteExterne = true;
String table = societeExterne instanceof GroupeIndustriel ? "GroupeIndustrielImpl" : "FournisseurImpl";
requete += " contractantExterne.id = :idsocieteExterne AND contractantExterne IN (FROM "+table+") ";
}
if (!"".equals(requete)) {
requete = "from ContratMddImpl where" + requete;
Query query = createQuery(requete);
if (!"".equals(anneeAccord)){
query.setBigInteger("anneeAccord", new BigInteger(anneeAccord));
}
if (!"".equals(typeAccord)){
query.setString("type", typeAccord);
}
if(existFamille){
query.setString("idFamilleDeProduit", String.valueOf(familleDeProduits.getFamilleDeProduitsGenerique().getId()));
}
if (existSocieteInterne){
query.setInteger("idsocieteInterne", societeInterne.getId());
}
if (existSocieteExterne){
query.setInteger("idsocieteExterne", societeExterne.getId());
}
listContratMdd.addAll((List<ContratMdd>) query.list());
}
return listContratMdd;
}
It is happening because the Postgre's DB Driver allows it. But you should be using setInt() instead of setString() for an Integer as other DB Drivers might not support it.
Here is what java.sql.PreparedStatement Documentation has to say:
Note: The setter methods (setShort, setString, and so on) for setting
IN parameter values must specify types that are compatible with the
defined SQL type of the input parameter. For instance, if the IN
parameter has SQL type INTEGER, then the method setInt should be used.

Categories

Resources