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.
Related
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.
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...
I want to update a parent table and simultaneously save data in child table in a single custom query in hibernate.
This is my serviceimplementation.
public int updateTimeTable(Map<String, Object> timeTable) {
int rows = timeTableDao.updateTimeTable(timeTable);
if(rows>2) {
rows = temptimeTableDao.updateTempTimeTable(timeTable);
}
return rows;
}
This are the query files(save customQuery):
public int updateTempTimeTable(Map<String, Object> map) {
Query query = customQuery("Insert into temp_time_table(employee_id,duration_till,duration_from,timetable_id)"
+ " values(:employeeId, :durationStart,:durationEnd,:timetableId)");
query.setLong("employeeId", Long.parseLong(map.get("employeeId").toString()));
query.setString("durationStart", map.get("durationStart").toString());
query.setString("durationEnd", map.get("durationEnd").toString());
query.setLong("timetableId", Long.parseLong(map.get("timetableId").toString()));
return query.executeUpdate();
}
updateTimeTable query:
public int updateTimeTable(Map<String, Object> map) {
if (map.isEmpty() && !map.containsKey("id"))
return 0;
String hql = "update TimeTable set ";
int count = 0;
String status = null;
if (map.containsKey("status") && map.get("status") != null) {
hql += "status = :status";
status = map.get("status").toString();
count++;
}
if (count == 0) {
return 0;
}
hql += " where id = " + map.get("id");
Query query = update(hql);
if (status != null) {
query.setString("status", status);
}
return query.executeUpdate();
}
I have a project which currently only does methods when I run the site. Now I need to implement a thread which checks the DB/the website for status-changes so I can send out a mail if something occurs. I have successfully added the functionality to mail someone, and also know the logic on how to do this. The problem occurs when I try to write the code, I don't know how to do it (Since I didn't know the back-end mostly, and now I have the responsibility for the project.
The logic would be to implement a java-thread (runnable) and then check the previous color with the new one and if it has changed send out an mail (The colors are statuses, for example, green & red). What is the most understandable and easy way to do this? I'll write the function names so you get an idea of what I have.
I have been stuck with this for a week and don't know what to do. Any help would be appreciated.
The method in the class for the object that changes color:
public void setColour(List<Status> statusar, List<Category> subcategories) {
for (int index = 0; index < subcategories.size(); index++) {
if (this.statusColor.compareToIgnoreCase("red") != 0) {
if ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("green") == 0)
&& (this.priority < ((Category)subcategories.get(index)).getPriority())) {
this.statusColor = "GREEN";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
if (((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 2))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("yellow") == 0)
&& (this.priority <= ((Category)subcategories.get(index)).getPriority()))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("yellow") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 3))) {
this.statusColor = "YELLOW";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
if (((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (((Category)subcategories.get(index)).getPriority() == 3))
|| ((((Status)statusar.get(index)).getStatusColor().compareToIgnoreCase("red") == 0)
&& (this.priority <= ((Category)subcategories.get(index)).getPriority()))) {
this.statusColor = "RED";
this.priority = ((Category)subcategories.get(index)).getPriority();
}
}
}
}
A color function I found in the DB part:
public List<Map<String, Object>> listColorsOverDays(String days, String categoryName) {
String SQL_getColors = "SELECT COUNT(*) count,color FROM ( ";
SQL_getColors += " SELECT CASE";
SQL_getColors += " WHEN CAST(status.value AS DECIMAL) >= CAST(greenFrom AS DECIMAL) AND CAST(status.value AS DECIMAL) <= CAST(greenTo AS DECIMAL) THEN 'GREEN' ";
SQL_getColors += " WHEN CAST(status.value AS DECIMAL) >= CAST(yellowFrom AS DECIMAL) AND CAST(status.value AS DECIMAL) <= CAST(yellowTo AS DECIMAL) THEN 'YELLOW' ";
SQL_getColors += " ELSE 'RED' END AS color ";
SQL_getColors += " FROM status INNER JOIN category ON status.idCategory = category.idCategory ";
SQL_getColors += " INNER JOIN threshold ON category.idCategory = threshold.idCategory ";
SQL_getColors += " WHERE status.timeStamp>DATE_SUB(NOW(), INTERVAL " + days + " DAY) ";
SQL_getColors += " AND category.name = '"+categoryName+"'";
SQL_getColors += " ) as p group by p.color";
List<Map<String, Object>> colorList = null;
try {
colorList = getJdbcTemplate().queryForList(SQL_getColors);
} catch (Exception e) {
e.printStackTrace();
}
return colorList;
}
Here's the controller which uses this function:
public List<Map<String, Object>> getColorList(String days, String categoryName) {
StatusDAO statusDao_i = (StatusDAO)this.context.getBean("statusDAO");
List<Map<String, Object>> colorList = new ArrayList();
try {
colorList = statusDao_i.listColorsOverDays(days, categoryName);
} catch (BadSqlGrammarException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return colorList;
}
A status list which contains the colors:
public List<Status> getStatusList(Status status) {
StatusDAO statusDao_i = (StatusDAO)this.context.getBean("statusDAO");
status.setCategoryId(this.categoryService_i.getCategoryId(status.getCategoryName()));
Timestamp fromTime = Timestamp.valueOf(status.getFromTime());
Timestamp toTime = Timestamp.valueOf(status.getToTime());
List<Status> statusList = new ArrayList();
try {
statusList = statusDao_i.getStatusesByTime(status, fromTime, toTime);
status.setCategoryId(this.categoryService_i.getCategoryId(status.getCategoryName()));
} catch (BadSqlGrammarException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return statusList;
}
I need to fetch data from multiple tables and export into excel sheet for each table. I don't want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().
For example
Object val = resultSet.getObject(i);
I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.
Can anyone please help me.
public class Row {
public Map<Object, Class> row;
public static Map<String, Class> TYPE;
static {
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("VARCHAR2", String.class);
}
public Row() {
row = new HashMap<Object, Class>();
}
public <t> void add(t data) {
row.put(data, data.getClass());
}
public void add(Object data, String sqlType) {
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
if(rs == null)
return;
ResultSetMetaData rsmd = rs.getMetaData();
int colCt = rsmd.getColumnCount();
while(rs.next()) {
Row row = new Row();
for(int i = 0; i < colCt; i++) {
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
public static void main(String[] args) {
}
}
Try this code:
Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
You should extend it with other datatypes.
Step 1: get the metadata
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++)
columnsType[i] = rsmd.getColumnType(i);
Step 2: fetch a row at a time from the result set and check the data type
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
s = rs.getString(i);
} else if (columnsType[i] == java.sql.Types.NVARCHAR) {
s = rs.getNString(i);
} else if (columnsType[i] == java.sql.Types.BOOLEAN) {
// TODO
} else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
// TODO
} else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
// TODO
} else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
// TODO
} else {
o = rs.getObject(i);
}
}
}
Step 3: fill the blanks and add the exception handling
Step 4: write to Excel (inside the loop)
public class EXECUTEQUERY implements Module {
private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private String userId;
String result = "";
String resp = "";
static int count = 1;
private final Logger log = Logger.getLogger("EXECUTEQUERY");
private void dbg(String msg) {
log.info(userId + ":" + msg);
}
private void dbg(Exception ex) {
log.info(ex.getMessage());
ex.printStackTrace();
}
private void uDbg(String msg) {
log.info(userId + " :" + msg);
}
private void uDbg(Exception ex) {
uDbg(ex.getMessage());
ex.printStackTrace();
}
public String main(UserContext userContext, String reqXml) {
dbg("Query recieved is " + reqXml);
String resp;
userId = userContext.getUserId();
if (userContext.getAction().equals("EXECUTEQUERY")) {
if (reqXml == null || reqXml.equals("")) {
result = "!Please Enter the query";
} else {
result = getQueryResult(userContext, reqXml);
}
}
return result;
}
/***
*
* for adding search record in backend created by #shyamlal yadav
* #param userContext
* #param reqXml
*/
public void addQueryLog(UserContext userContext, String reqXml) {
dbg("inside addQueryLog methos request is " + reqXml);
userId = userContext.getUserId();
dbg( userId +"this user is selecting value from screen");
System.out.println("recieve request is " + reqXml);
PreparedStatement pStmt = null;
Connection eodConn = null;
dbg("addQueryLog recieved for log " + reqXml);
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime());
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
+ " values (?,?,?)");
pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
pStmt.setString(2, reqXml);
pStmt.setString(3, userId);
pStmt.executeQuery();
} catch (SQLException ex) {
dbg("Exception is " + ex);
return;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
return;
}
/*
This method returns query excecuted table data with separators.
#Shaymlal,
*/
public String getQueryResult(UserContext userContext, String reqXml) {
String field_value = "";
String lsitofquery = "";
String resultlist = "";
dbg("Inside getQueryResult method");
Connection eodConn = null;
Statement stmt = null;
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(reqXml);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
dbg("Total no of column is:" + columnCount);
int rsCount = 1;
while (rs.next()) {
if (rsCount == 1) {
for (int i = 1; i <= columnCount; i++) {
resultlist += "~" + rsmd.getColumnName(i);
}
}
for (int i = 1; i <= columnCount; i++) {
field_value += "~" + rs.getString(i);
}
field_value = field_value + "~<>";
lsitofquery = resultlist + "~>" + field_value;
rsCount = rsCount + 1;
}
} catch (Exception ex) {
dbg("Exception is " + ex);
return "!Exception invalid query: " + ex;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
// return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
addQueryLog(userContext,reqXml);
return lsitofquery + ">";
}
}