Updating and Saving in a Single Query in Hibernate - java

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();
}

Related

What does "my_something" means in oracle sql query?

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.

how to improve the interaction between two Hash Map in java?

In the below code I am fetching the objects from the hive and passing the tbl_guid to fetch the matches in Mysql and Map will be returned as contains Map<tbl_guid ,uniqueseq>, then the on the based of tbl_guid as key already present the map dRListMap value List<DeletedRecord> DeletedRecord object property tbl_guid will be updated with fetched the uniqueseq fetched from the mysql.
Why am I replacing the tbl_guid with uniqueSeq fetching from the mysql because the on the based with small no corresponding to every tbl_guid which will stored in the HBase later of this, that part of code is not required herein discussion so I haven't posted? I would like to know where is enhancement is required current code.
1st Method
String sql = String.format("select * from %s .HiveTable limit 12", dbName);
Map<String, List<DeletedRecord>> dRListMap = new HashMap<>();
try (Statement stmt = hiveConnection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
int i=0;
while ((rs.next())) {
DeletedRecord delRecord = new DeletedRecord(rs.getString(1), rs.getString(2), rs.getString(3),
rs.getString(4), rs.getDate(5));
String key = rs.getString(2);
List<DeletedRecord> recordList = dRListMap.get(key) == null ? new ArrayList<>() : dRListMap.get(key);
recordList.add(delRecord);
dRListMap.put(key, recordList);
i++;
if (i == 10) {
CommonService.fetchUniquForTblGuid(dRListMap);
i=0;
}
}if(i>0) {
CommonService.fetchUniquForTblGuid(dRListMap);
}
} catch (Exception ee) {
LOGGER.error("Exception occurred while fetching the records from table_name", ee);
}
2nd Method
public static void fetchUniquForTblGuid(Map<String, List<DeletedRecord>> dRListMap) {
List<List<DeletedRecord>> valueList = Collections.list(Collections.enumeration(dRListMap.values()));
List<String> values = valueList.stream().flatMap(Collection::stream).map(DeletedRecord::getTblGuid)
.collect(Collectors.toCollection(ArrayList::new));
Map<String, String> tblSeqMap = getTheUniqueNoForGuids(values);
System.out.println(dRListMap);
for (Map.Entry<String, String> map : tblSeqMap.entrySet()) {
if (dRListMap.containsKey(map.getKey())) {
dRListMap.get(map.getKey()).forEach((DeletedRecord del)->del.setTblGuid(map.getValue()));
}
}
System.out.println(dRListMap);
dRListMap.clear();
}
3rd Method
public static Map<String, String> getTheUniqueNoForGuids(List<String> tableGuids) {
Map<String, String> guidVsUnique = new HashMap<>();
String tableGuidStr = listToCommaDelimitedString(tableGuids);
String fetchthequniforguid = "select distinct tbl_guid,unique_sequ from " + sqlProp.getProperty("database")
+ ".mysql table where tbl_guid in (" + tableGuidStr + ")";
try (PreparedStatement prep = mysqlConnection.prepareStatement(fetchthequniforguid);
ResultSet res = prep.executeQuery()) {
LOGGER.info(String.format("Mysql query %s ", fetchthequniforguid));
while (res.next()) {
guidVsUnique.put(res.getString(1), res.getString(2));
}
} catch (SQLException e) {
LOGGER.info(String.format("Error while executing %s in mysql and occurred %s ", fetchthequniforguid, e));
}
return guidVsUnique;
}
4th Method
public static String listToCommaDelimitedString(List<String> requestIds) {
StringBuffer buffer = new StringBuffer();
if (requestIds.size() == 1)
buffer.append("'" + requestIds.get(0) + "'");
else if (requestIds.size() > 1) {
buffer.append("'");
for (int i = 0; i < requestIds.size(); i++) {
if (i == requestIds.size() - 1)
buffer.append(requestIds.get(i) + "'");
else
buffer.append(requestIds.get(i) + "', '");
}
}
return buffer.toString();
}

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...

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.

Fetch an entire row with jdbc as a List

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 + ">";
}
}

Categories

Resources