Java SQL Resultset DataTypes - java
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.
Related
Querying through java
I have two tables: harvested_record and harvested_record_simple_keys there are in relation one-to-one. harvested_record id|harvested_record_simple_keys_id|a lot of columns harvested_record_simple_keys id| a lot of columns and I want to make a query in which I need to join there two tables. As a result I will have a table: joined_table id(harvested_record)| (harvested_record_simple_keys)|a lot of columns. Unfortunately I get an exception: nested exception is java.sql.SQLSyntaxErrorException: Column name 'ID' matches more than one result column. I've understood this is because after join I will have two columns 'id'. Does anyone can help me with solution? P.S. SQL statement(works in IDEA console): SELECT * FROM ( SELECT TMP_ORDERED.*, ROW_NUMBER() OVER () AS ROW_NUMBER FROM (SELECT * FROM harvested_record hr JOIN harvested_record_simple_keys hrsk ON hrsk.id = hr.harvested_record_simple_keys_id WHERE import_conf_id = ? ) AS TMP_ORDERED) AS TMP_SUB WHERE TMP_SUB.ROW_NUMBER <= 2 ORDER BY import_conf_id ASC, record_id ASC; Java code(suppose error is here): JdbcPagingItemReader<HarvestedRecord> reader = new JdbcPagingItemReader<HarvestedRecord>(); SqlPagingQueryProviderFactoryBean pqpf = new SqlPagingQueryProviderFactoryBean(); pqpf.setDataSource(dataSource); pqpf.setSelectClause("SELECT *"); pqpf.setFromClause("FROM harvested_record hr JOIN harvested_record_simple_keys hrsk ON hrsk.id = hr.harvested_record_simple_keys_id"); String whereClause = "WHERE import_conf_id = :configId"; if (from!=null) { fromStamp = new Timestamp(from.getTime()); whereClause += " AND updated >= :from"; } if (to!=null) { toStamp = new Timestamp(to.getTime()); whereClause += " AND updated <= :to"; } if (configId != null) { pqpf.setWhereClause(whereClause); } pqpf.setSortKeys(ImmutableMap.of("import_conf_id", Order.ASCENDING, "record_id", Order.ASCENDING)); reader.setRowMapper(harvestedRecordRowMapper); reader.setPageSize(PAGE_SIZE); reader.setQueryProvider(pqpf.getObject()); reader.setDataSource(dataSource); if (configId != null) { Map<String, Object> parameterValues = new HashMap<String, Object>(); parameterValues.put("configId", configId); parameterValues.put("from", fromStamp ); parameterValues.put("to", toStamp); reader.setParameterValues(parameterValues); } reader.afterPropertiesSet(); Thank you in advance.
If you name your columns in the select statement instead of using 'SELECT *', you can omit the ID from one of the tables since it is always equal to the id from the other table.
getting data from result set is too slow
Fetching data from PostgreSQL database with Result Set is too slow. Here is my code. for (int i = 0; i < qry_list.size(); i++) { try { resultSet = statement.executeQuery(qry_list.get(i)); resultSet.setFetchSize(0); while (resultSet.next()) { totalfilecrated = totalfilecrated + resultSet.getInt(columnname); } } catch (SQLException e) { e.printStackTrace(); } } Here I try to fetch data inside a for loop.is it good? Here is my query. For getting ID of individual Organisations(org_unit_id). "select org_unit_id from emd.emd_org_unit where org_unit_id in(select org_unit_id from emd.emd_org_unit_detail where entity_type_id=1 and is_active=true) and is_active=true order by org_unit_name_en"; Then i want to get the count of files with each org_unit_id select count(*) as totalfilecreatedelectronic from fl_file ff left join vw_employee_details_with_department epd on epd.post_detail_id=ff.file_opened_by_post_fk where ff.file_nature = 'E' and ((ff.migration_date>='2011-01-01' and ff.migration_date<='2015-01-01') or (ff.opening_date >='2011-01-01' and ff.opening_date <='2015-01-01')) and epd.departmentid=org_unit_id";
Seeing how your second query already contains a reference to a column that's an org_unit_id, you might think joining emd_org_unit table in directly: select org.org_unit_id, count(*) as totalfilecreatedelectronic from fl_file ff left join vw_employee_details_with_department epd on epd.post_detail_id=ff.file_opened_by_post_fk -- join to active entries in emd_org_unit inner join from emd.emd_org_unit org ON epd.departmentid=org.org_unit_id AND org.is_active=true where ff.file_nature = 'E' and ( (ff.migration_date>='2011-01-01' and ff.migration_date<='2015-01-01') or (ff.opening_date >='2011-01-01' and ff.opening_date <='2015-01-01')) -- and now group by org_unit_id to get the counts group by org_unit_id If you'd create a SQLFiddle for this, things would get much clearer I guess.
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) {}
JDBC Error (SQL syntax) Parameter index out of range (2 > number of parameters, which is 1) [duplicate]
This question already has answers here: java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed] (2 answers) Closed 6 years ago. Im getting this unkown error when running this code: String SELECT_getWhenValueChanged = "SELECT a.* FROM status AS a WHERE a.value <> (SELECT b.value FROM status AS b WHERE a.idCategory = ? AND b.idCategory = a.idCategory and a.timeStamp > b.timeStamp ORDER BY b.timeStamp DESC LIMIT 1) ORDER BY timeStamp DESC"; try { Survey surveyTemp = new Survey(); surveyTemp = (Survey) getJdbcTemplate() .queryForObject(SELECT_getWhenValueChanged, new Object[] { categoryId, categoryId }, new SurveyMapper()); /* * SQL Question ask when the value has changed and get the value * that changed from and changed to, the first one is the current * value and the second is the value before it changed */ if (!surveyTemp.getTimestamp().isEmpty() && !presentSurvey.getTimestamp().isEmpty()) { presentSurvey.setTimestamp(surveyTemp.getTimestamp()); } } catch (BadSqlGrammarException e) { e.printStackTrace(); } catch (EmptyResultDataAccessException e) { } catch (Exception e) { e.printStackTrace(); } return presentSurvey; Anybody know what this means? org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [SELECT a.* FROM status AS a WHERE a.value <> (SELECT b.value FROM status AS b WHERE a.idCategory = ? AND b.idCategory = a.idCategory and a.timeStamp > b.timeStamp ORDER BY b.timeStamp DESC LIMIT 1) ORDER BY timeStamp DESC]; Parameter index out of range (2 > number of parameters, which is 1).; nested exception is java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1). Im not good at SQL, so dont know how to solve this...
Since there is only one parameter in your PreparedStatement, you should not pass two parameters into it. Maybe you can change new Object[] { categoryId, categoryId } into new Object[] { categoryId }.
changed it to String SELECT_getWhenValueChanged = "SELECT a.* FROM status AS a WHERE a.idCategory = ? AND a.value = ? AND a.timeStamp > (SELECT b.timeStamp FROM status AS b WHERE b.idCategory = ? and b.value <> ? ORDER BY timeStamp DESC LIMIT 1) ORDER BY timeStamp ASC LIMIT 1"; try { Survey surveyTemp = (Survey) getJdbcTemplate().queryForObject(SELECT_getWhenValueChanged, new Object[] { categoryId, presentSurvey.getValue(), categoryId, presentSurvey.getValue() }, new SurveyMapper()); And that worked! thanks
// In Spring DAO Module using On that time these Exception is raised // Correct Code public StudentRegistrationBean select(int studentId) { StudentRegistrationBean queryForObject = jdbcTemplate.queryForObject( "SELECT * FROM STUDENTREGISTRATION WHERE STUDENTID=?", new Object[] { studentId }, new BeanPropertyRowMapper<StudentRegistrationBean>( StudentRegistrationBean.class)); return queryForObject; // Wrong Code public StudentRegistrationBean select(int studentId) { StudentRegistrationBean queryForObject = jdbcTemplate.queryForObject( "SELECT * FROM STUDENTREGISTRATION WHERE STUDENTID=?", new Object[] { studentId }, new BeanPropertyRowMapper<StudentRegistrationBean>( StudentRegistrationBean.class)); return null; Conclusion: if you are retuning values you might mistake in put "null" type of values... Means Some thing Make Mistake Methods Writing (OR) return null values
getting error that nested exception is org.hibernate.hql.ast.QuerySyntaxException: Path expected for join
I am new to hibernate and I have a query select * from Losa_App a inner join os_historystep os on a.app_ref_no = os.ref_id where os.step_name = '011' and app_status = 'R' or app_status = 'S' ; when i run this query on sqldeveloper it runs and give me the results. Now i translated the query into HBL like StringBuffer query = new StringBuffer(); List<String> lstObj = new ArrayList<String>(); query.append(" from "); query.append(getClassName()); query.append(" a inner join " // + WflWorkflowHistoryStep.class.getName() + " OS_HISTORYSTEP os with a.appRefNo = os.ref_id " + "where os.step_name = '011' and a.appStatus = 'R' or a.appStatus = 'S' "); List<LosaApp> result = null; try { result = getHibernateTemplate().find(query.toString()); if (CollectionUtils.isNotEmpty(result) { return result; } } catch (Exception e) { String message = e.getMessage(); System.out.println(); } return null; But when this query runs i get exception that nested exception is org.hibernate.hql.ast.QuerySyntaxException: Path expected for join! [ from com.thetasp.losa.data.LosaApp a inner join OS_HISTORYSTEP os with a.appRefNo = os.ref_id where os.step_name = '011' and a.appStatus = 'R' or a.appStatus = 'S' ] Why i am getting this error ? Thanks
Your HQL syntax is wrong. You need to specify the alias by using the keyword as. E.g:- Losa_App as a If you give inner join, and have your association mappings done, then you needn't provide the on clause. If you want to give a.app_ref_no = os.ref_id, then you need not specify inner join. Hibernate will take care of that. For more info, do have a look at this question.