I've already searched other problems related to this but I've just realized that maybe it's in the query of mine perhaps that this problem occurred or in the hibernate
SEE The where clause, it hasn't been called yet its there
what could be the problem?
Here is the whole code
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(checkAllNotEmpty(data)) {
query = query.concat("WHERE ");
if(data.getEmployeeID() != null && !data.getEmployeeID().equals("")) {
criteria.add(CRITERIA_EMPLOYEEID2);
System.out.println("Employee IDs");
input_empID = true;
}
if(data.getEmployeeName()!= null && !data.getEmployeeName().equals("")){
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;
}
So Help T.T
Related
How can I only make my application execute the changes to a database at the end of the while cycle?
I have this rollback method but I only the changes to be made to the database at the end of it because of inconsistent data handling
I have tried to set auto commit to false but even though the exception was thrown at the second iteration of the while cycle, the changes were still in the database(until the point before the interruption, the tables after that didn't suffer changes).
Am I doing something wrong?
#Override
public void rollback(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
try {
connection.setAutoCommit(false);
ResultSet rs = getTables(connection);
//if the user chose to use a suffix
if (this.getSuffix() != null) {
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.getSuffix())) {
if (!checkColumnsExists(connection, tableName, newName)) {
throw new CustomChangeException("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
//if the user chose to use a regex
if (this.getRegex() != null) {
Pattern pattern = Pattern.compile(this.getRegex());
while (rs.next()) {
String tableName = rs.getString(3);
Matcher matcher = pattern.matcher(tableName);
boolean matches = matcher.matches();
if (matches) {
if (!checkColumnsExists(connection, tableName, newName)) {
logger.error("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
throw new CustomChangeException();
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
connection.commit();
} catch (SQLException | DatabaseException | DifferentDataTypeException e) {
logger.error(e.getMessage());
throw new CustomChangeException();
}
}
public List getPayslipsOfEmployees(String empids, Date paydate) {
initializeTransaction();
String strSQL = "SELECT "
+ " pd.* "
+ " FROM "
+ " payroll_d pd "
+ " INNER JOIN "
+ " payroll_h ph "
+ " ON pd.pay_uid = ph.pay_uid "
+ " WHERE pd.employee_id IN ("+empids+") "
+ " AND ph.pay_date = DATE('"+sql_dateformat.format(paydate)+"')";
SQLQuery q = session.createSQLQuery(strSQL);
q.addEntity("pd", PayrollD.class);
List pdlist = q.list();
commit();
List<Payslip> pslips = new ArrayList<Payslip>();
if (!pdlist.isEmpty()) {
Iterator it = pdlist.iterator();
while (it.hasNext()) {
try {
PayrollD payd = (PayrollD)it.next();
Payslip ps = new Payslip();
ps.setDepartment(payd.getEmployeeCatalog().getDepartmentCatalog().getDeptName());
ps.setEmployeeID(payd.getEmployeeCatalog().getEmployeeId());
ps.setEmployeeName(payd.getEmployeeCatalog().getEmpLastname(), payd.getEmployeeCatalog().getEmpFirstname(), payd.getEmployeeCatalog().getEmpMiddlename());
ps.setStartPayPeriod(payd.getPayrollH().getPayFromdate());
ps.setEndPayPeriod(payd.getPayrollH().getPayTodate());
ps.setDesignation(payd.getEmployeeCatalog().getJobDesignation());
EmployeeExemption exmptn = (EmployeeExemption)getCurrentExemption(payd.getEmployeeCatalog().getEmployeeId());
ps.setExemption((exmptn != null) ? exmptn.getExemptionCode() : SysConstants.DEFAULT_EXEMPTION);
List<PayslipEarning> earnings = new ArrayList<PayslipEarning>();
List<PayslipDeduction> deductions = new ArrayList<PayslipDeduction>();
ps.setNetPay(getPayslipNetPay(payd, earnings, deductions));
ps.setPrevTotalTaxableEarning(getPrevTotalTaxableEarning(payd));
ps.setTotalWithheld(getTotalWithheld(payd));
ps.setEarnings(earnings);
ps.setDeductions(deductions);
pslips.add(ps);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Somethings wrong " + e.getMessage());
}
}
}
return pslips;
}
I am getting this function by this funtion
private void generatePaySummary() {
try {
Map params = new HashMap();
params = getOrganizationInfo(params);
params.put("rptsubtitle", "Payroll Date: "+date_formatter.format(tbpaydate.getDate()));
int i = cboDept.getSelectedIndex();
int deptno = 0;
if (i != -1) deptno = (Integer)deptnos.get(i);
ReportService srv = new ReportService();
List empids = srv.getEmployeesInPayroll(deptno, tbpaydate.getDate());
if (!empids.isEmpty()) {
PayslipService.setEmployees(empids);
PayslipService.setPayDate(tbpaydate.getDate());
RepGenService repsrv = new RepGenService();
JRBeanCollectionDataSource jbsrc = new JRBeanCollectionDataSource(PaySummaryFactory.getPaySummary());
repsrv.generateReport(false, "/orgpayroll/reports/jasper/payrollsummary.jasper", true, params, jbsrc);
}
else
SysUtils.messageBox("No employees in payroll on "+date_formatter.format(tbpaydate.getDate())+"!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error" + e.getMessage());
}
}
When I try to run this function to get the payroll and employee information of the employee, it says Hibernate could not initialize proxy - no session. I can't find which one is causing the error. It works when I only process one employee of the same date, but when I process two employees on the same date, the error occurs.
This method is working perfectly as my requirement.But I want to query with DB only once.
I have 2 conditions to check with DB for querying and displaying List data in UI.Each time I am accessing DB and checking list size and performing action.
For one data list with same table I am querying 3 times.Which is not efficient way I think. And wrote sub queries for it.But could not succeed with it.
So any efficient way for writing this and optimizing my method..?
query1: "FROM Produce where produceId not in (:produceIdList) and itemName in (:itemNameList)" + " and farmerUuid not in(" + merchantUuid + ") and lastDateForBid>=CURDATE() order by lastDateForBid Asc";
Condition: If(result>=10) return data
else check for query2
query2: "FROM Produce where produceId not in (:produceIdList) and farmerUuid not in(" + merchantUuid + ")" + "and itemName in (:itemNameList) and categoryId in (:categoryList) and lastDateForBid>=CURDATE() order by lastDateForBid Asc";
Condition: If(result>=10) return data
else check for query3
query3:
"FROM Produce where produceId not in (:produceIdList) and farmerUuid not in(" + merchantUuid + ") and lastDateForBid>=CURDATE() order by lastDateForBid Asc ";
This is my method
mId = merchantUuid;
Long produceId = null;
String itemName = null;
Long categoryId = null;
List<Long> categoryList = new ArrayList<Long>();
List<Long> produceIdList = new ArrayList<Long>();
List<Produce> produceList = new ArrayList<Produce>();
List<String> itemNameList = new ArrayList<String>();
List<Bidding> biddingList = getBiddingForMerchant();
int count = biddingList.size();
if (count > 0) {
for (int i = 0; i < count; i++) {
produceId = biddingList.get(i).getProduce().getProduceId();
if(!produceIdList.contains(produceId)){
produceIdList.add(produceId);
}
itemName = biddingList.get(i).getProduce().getItemName();
if (!itemNameList.contains(itemName)) {
itemNameList.add(itemName);
}
categoryId = biddingList.get(i).getProduce().getCategory().getCategoryId();
if (!categoryList.contains(categoryId)) {
categoryList.add(categoryId);
}
}
String ProduceQuery1 = "FROM Produce where produceId not in (:produceIdList)"
+ " and itemName in (:itemNameList)" + " and farmerUuid not in(" + merchantUuid + ")"
+ " and lastDateForBid>=CURDATE() order by lastDateForBid Asc";
Query q1 = sessionFactory.getCurrentSession().createQuery(ProduceQuery1);
q1.setParameterList("itemNameList", itemNameList);
q1.setParameterList("produceIdList", produceIdList);
//q1.setMaxResults(10);
#SuppressWarnings("unchecked")
List<Produce> produceList1 = q1.list();
produceList.addAll(produceList1);
if (produceList.size() ==10) {
return produceList;
}
else if (produceList.size() < 10) {
String produceQuery2 = "FROM Produce where produceId not in (:produceIdList)"
+ " and farmerUuid not in(" + merchantUuid + ")" + "and itemName in (:itemNameList)"
+ " and categoryId in (:categoryList) "
+ " and lastDateForBid>=CURDATE() order by lastDateForBid Asc";
Query q2 = sessionFactory.getCurrentSession().createQuery(produceQuery2);
System.out.println("produceQuery::" + produceQuery2);
q2.setParameterList("produceIdList", produceIdList);
q2.setParameterList("itemNameList", itemNameList);
q2.setParameterList("categoryList", categoryList);
//q2.setMaxResults(10);
#SuppressWarnings("unchecked")
List<Produce> produceList2 = q2.list();
produceList.clear();
produceList.addAll(produceList2);
if (produceList.size() > 9) {
List<Produce> produceListNew = produceList.subList(0,10);
return produceListNew;
}
else {
String produceQuery3 = "FROM Produce where produceId not in (:produceIdList)"
+ " and farmerUuid not in(" + merchantUuid + ")"
+ " and lastDateForBid>=CURDATE() order by lastDateForBid Asc ";
Query q3 = sessionFactory.getCurrentSession().createQuery(produceQuery3);
q3.setParameterList("produceIdList", produceIdList);
//q3.setMaxResults(10);
#SuppressWarnings("unchecked")
List<Produce> produceList3 = q3.list();
produceList.clear();
produceList.addAll(produceList3);
if(produceList.size()>10){
produceList = produceList.subList(0,10);
}
return produceList;
}
}
}
Thank you..!!
protected void saveData() {
Map<String, String> allStationsParams = new HashMap<>();
List<String> stations = getAllStations();
stmt = Database.getUpdateableStatement();
today = (SysTime.currentTimeMillis() / DasStamp.TICKS_PER_DAY) *
DasStamp.TICKS_PER_DAY;
String changeTimestamp = DasStamp.asCompactString(today);
String keyName = "COM.MAPPINGTOOLTIP." + attributeValue;
for (int row = 0; row < this.getTableModel().getRowCount(); row++) {
String station = (String)this.getTableModel().getValueAt(row, 0);
putInStationParams(this, station, allStationsParams, row);
}
for (String station : stations) {
boolean sendToDB = false;
try (ResultSet rs = this.rsParameters) {
rs.beforeFirst();
while (rs.next()) {
if (rs.getString("station").equals(station)) {
sendToDB = true;
break;
}
}
if (sendToDB) {
if (!rs.getString("value_text").equals(allStationsParams.get(station)) || !allStationsParams.containsKey(station)) {
sendToDB = true;
} else {
sendToDB = false;
}
} else if (allStationsParams.containsKey(station)) {
sendToDB = true;
}
if (sendToDB) {
String sql = "REPLACE INTO dss_parameter (key_name, station, valid_from, value_text"
+ ", change_timestamp) VALUES ('"
+ keyName + "','" + station + "','" + DasStamp.asDateOnlyString(today) + "','"
+ Helper.nz(allStationsParams.get(station)) + "','"
+ changeTimestamp + "') ;";
if (null != stmt) {
stmt.execute(sql);
if (!isResultSetEmpty(rs) && !rs.isAfterLast()) {
AdminLogger.log("dss_parameter", Action.UPDATE,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"value_text='" + rs.getString("value_text") + "'",
"value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
} else {
AdminLogger.log("dss_parameter", Action.INSERT,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"", "value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
}
}
}
} catch (SQLException e) {
AppFrame.msgBox("Error on insert: " + e.getMessage());
Helper.printMessage(true, false, "Parameter save failed!!", e);
}
}
}
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
Your rsParameters parameter is of Type Resultset.
In first iteration, after try{} block is complete close() method of rsParameters:ResultSet is called.
This internally makes all the properties of resultSet NUll.
That is the reason for getting Null properties during second iteration.
SEE: http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.27/com/mysql/jdbc/ResultSetImpl.java#ResultSetImpl.realClose%28boolean%29
I've come across a weird situation. The code is as below:
public static int add(String trcd, String tlcd, String dept, String doDate,
String doTime, String andConfirm, Teller admin) throws
Exception {
try {
String table1 = "table1";
String table2 = "table2";
String trap = null;
String trtype = null;
String sql = "select * from " + table2;
DataSet dataset = DBOper.DBQuery("taUtil", sql);
if (dataset.isEmpty()) {
return -1;
}
else {
HashMap map = dataset.getRow(0);
trap = (String) map.get("aut_ap_code");
trtype = (String) map.get("aut_type_code");
//point 1
sql = "insert into " + table1 + " values("+trtype + "','" + doDate + "','" + doTime + "','N','Y')";
DBOper.DBUpdate("taUtil", sql);
if (andConfirm.equals("Y")) {
//point 2
sql = "select * " + table1 +" where tr_create_date='" + doDate + "' and tr_create_time='" + doTime + "' and tr_stcd='Y'";
//point 3
DataSet dataset2 = DBOper.DBQuery("taUtil", sql);
if (dataset2.isEmpty()) {
return -2;
}
else {
String trNo = null;
HashMap map2 = dataset2.getRow(0);
trNo = (String) map2.get("tr_no");
confirm(admin, trNo, "N");
}
}
return 0;
}
}
catch (Exception e) {
throw e;
}
}
The problem is:
at point 3, it
always prints "insert" ie the previous sql value instead of the latest assignment of "select".
Does anybody knows why is it so ?
Thanks
You have a syntax error in your assignment statement:
sql = "insert into " + table1 + " values(trtype + "','" + doDate + "','" + doTime + "','N','Y')";
Try to replace it with:
sql = "insert into " + table1 + " values(" +trtype + "',' " + doDate + "','" + doTime + "','N','Y')";
I'm not sure how you even managed to compile this...
EDIT: If this syntax error does stop the code from compiling and your IDE (assuming you are using one) executes older version of the class that could not be compiled (has happened to me using Eclipse on occasions), I think it could end up doing something completely unpredictable and possibly explain this odd behavior.