Exception in java using dao class to get row - java

My DAO Class:
#SuppressWarnings("unchecked")
public int getRowCount(Map<String, Object> searchParam) throws DAOReadException {
List<Client> clientRow = null;
try {
Criteria criteria = Criteria.forClass(Client.class);
//set criteria search
for (String key : searchParam.keySet()) {
/*if(key.equals("ClientPK.clientId1")){
criteria.add(Restrictions.like("ClientPK.clientId", searchParam.get(key)));
}*/
if(key.equals("clientPK.clientId")){
criteria.add(Restrictions.eq(key, Integer.parseInt(searchParam.get(key).toString())));
}
if(key.equals("clientName")){
criteria.add(Restrictions.like(key, searchParam.get(key)));
}
if(key.equals("status")){
criteria.add(Restrictions.eq(key, Short.parseShort(searchParam.get(key).toString())));
}
//Bug# 12544 start
if(key.equals("orgId"))
{
criteria.add(Restrictions.eq("ClientPK.orgId", searchParam.get(key)));
}
//Bug# 12544 End
}
criteria.addOrder(Order.desc("createdDate"));
clientRow = (List<Client>) findByCriteria(criteria);
}
catch (Exception e) {
throw new DAOReadException(e);
}
int rowCount = 0;
if (clientRow != null) {
rowCount = clientRow.size();
}
return rowCount;
}
}
error is :
java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: ClientPK of: com.vin.eretail.model.client.Client [select this from com.vin.eretail.model.client.Client as this where this.ClientPK.orgId=? order by this.createdDate desc]

seems to change like below:
//Bug# 12544 start
if(key.equals("orgId"))
{
criteria.add(Restrictions.eq("clientPK.orgId", searchParam.get(key)));
}
//Bug# 12544 End
still need to see your Client class

Related

How to get value of a cell by column name in java using azure-kusto-java library

public KustoResultSetTable executeKustoQuery(ClientImpl client, String query) {
KustoResultSetTable mainTableResult = null;
try {
KustoOperationResult results = client.execute(databaseName, query);
mainTableResult = results.getPrimaryResults();
} catch (DataServiceException | DataClientException e) {
errorHandler(e, "Error while retrieving results from kusto query!");
}
return mainTableResult;
}
The above code returns me a result of this type
Name | Age
XYZ AAA | 29
How can I get the value of 1st row under name column using Azure Kusto Java mainTableResult object
Expected String output - "XYZ AAA"
You can do:
if (mainTableResult.first()) {
int columnIndex = mainTableResult.findColumn("Name")
return mainTableResult.getString(columnIndex);
} else {
throw new UnsupportedOperationException(""); // Or any other error handling
}
A complete version is:
public String executeKustoQuery(ClientImpl client, String query) {
KustoResultSetTable mainTableResult = null;
try {
KustoOperationResult results = client.execute("databaseName", query);
mainTableResult = results.getPrimaryResults();
if (mainTableResult.first()) {
int columnIndex = mainTableResult.findColumn("Name")
return mainTableResult.getString(columnIndex);
} else {
throw new UnsupportedOperationException(""); // Or any other error handling
}
} catch (DataServiceException | DataClientException e) {
errorHandler(e, "Error while retrieving results from kusto query!");
}
}

I want to insert 11000 records in chunks of 1000 using JDBI such that all should persist or none at all .It gives error currently as follows

My code is like
Class Employee
{
#ColumnName("empid")
public int empid;
#ColumnName("empname")
public String empname;
#ColumnName("experience")
public int experience;
}
then
List<Employee> lstEmployee = new ArrayList<>();
for (int i = 1; i < 10000; i++) {
lstEmployee.add(new Employee(i, "abcazsa", i));
}
UserDAOImpl obj = new UserDAOImpl(new JdbiHelper().getDBI());
obj.insertrecords(lstEmployee);
and
#BatchChunkSize(1000)
int insertRecords(#BindBeanList(propertyNames = {"empid", "empname", "experience"}, value = "values") List<Employee> lstEmp);
and last
public int insertrecords(List<Employee> lstEmp)
{
int cnt = 0;
try (Handle open = jdbi.open()) {
UserDAO attach = open.attach(UserDAO.class);
}
catch(Exception e)
{
throw e;
}
System.out.println("After catch");
return cnt;
}
}
Exception in thread "main" org.jdbi.v3.core.statement.UnableToExecuteStatementException: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend. [statement:"INSERT INTO public."Employee" (empid, empname, experience) VALUES <values>", rewritten:"INSERT INTO public."Employee" (empid, empname, experience) VALUES (:__values_0_empid,:__values_0_empname,:
finder:[]}]
at org.jdbi.v3.core.statement.SqlStatement.internalExecute(SqlStatement.java:1464)
at org.jdbi.v3.core.result.ResultProducers.lambda$returningUpdateCount$0(ResultProducers.java:39)
at org.jdbi.v3.core.statement.Update.execute(Update.java:53)
at org.jdbi.v3.core.statement.Update.execute(Update.java:41)
at org.jdbi.v3.sqlobject.statement.internal.SqlUpdateHandler.lambda$new$1(SqlUpdateHandler.java:59)
at org.jdbi.v3.sqlobject.statement.internal.SqlUpdateHandler.lambda$configureReturner$3(SqlUpdateHandler.java:74)
at org.jdbi.v3.sqlobject.statement.internal.CustomizingStatementHandler.invoke(CustomizingStatementHandler.java:157)
at org.jdbi.v3.sqlobject.statement.internal.SqlUpdateHandler.invoke(SqlUpdateHandler.java:30)
at org.jdbi.v3.sqlobject.SqlObjectFactory.lambda$null$13(SqlObjectFactory.java:162)
at org.jdbi.v3.core.ConstantHandleSupplier.invokeInContext(ConstantHandleSupplier.java:52)
at org.jdbi.v3.sqlobject.SqlObjectFactory.lambda$createInvocationHandler$14(SqlObjectFactory.java:161)
at com.sun.proxy.$Proxy11.insertRecords(Unknown Source)
at com.samples.UserDAOImpl.insertrecords(UserDAOImpl.java:48)
at com.samples.BulkInsert.main(BulkInsert.java:28)
Suppressed: org.jdbi.v3.core.transaction.TransactionException: Failed to test for transaction status
at org.jdbi.v3.core.transaction.LocalTransactionHandler.isInTransaction(LocalTransactionHandler.java:134)
at org.jdbi.v3.core.Handle.isInTransaction(Handle.java:259)
at org.jdbi.v3.core.Handle.close(Handle.java:123)
at com.samples.UserDAOImpl.insertrecords(UserDAOImpl.java:57)
... 1 more
Caused by: org.postgresql.util.PSQLException: This connection has been closed.
at org.postgresql.jdbc.PgConnection.checkClosed(PgConnection.java:767)
at org.postgresql.jdbc.PgConnection.getAutoCommit(PgConnection.java:728)
at org.jdbi.v3.core.transaction.LocalTransactionHandler.isInTransaction(LocalTransactionHandler.java:131)
... 4 more
Caused by: org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:333)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:155)
at org.postgresql.jdbc.PgPreparedStatement.execute(PgPreparedStatement.java:144)
at org.jdbi.v3.core.statement.SqlStatement.internalExecute(SqlStatement.java:1451)
... 13 more
Caused by: java.io.IOException: Tried to send an out-of-range integer as a 2-byte value: 32997
at org.postgresql.core.PGStream.sendInteger2(PGStream.java:224)
at org.postgresql.core.v3.QueryExecutorImpl.sendParse(QueryExecutorImpl.java:1440)
at org.postgresql.core.v3.QueryExecutorImpl.sendOneQuery(QueryExecutorImpl.java:1762)
at org.postgresql.core.v3.QueryExecutorImpl.sendQuery(QueryExecutorImpl.java:1326)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:298)
... 18 more
It gets solved by using transaction process.
the code is like below
public int insertrecords(List<Employee> lstEmp) {
int cnt = 0;
Handle open = null;
try {
open = jdbi.open();
open.begin();
UserDAO attach = open.attach(UserDAO.class);
System.out.println("Start");
while (true) {
List<Employee> lstTemp = lstEmp.stream()
.limit(3000).collect(Collectors.toList());
int tempcnt = attach.insertRecords(lstTemp);
lstEmp.removeAll(lstTemp);
cnt = cnt + tempcnt;
if (lstEmp.isEmpty()) {
break;
}
}
if (open != null && open.isInTransaction()) {
System.out.println("Commit");
open.commit();
}
System.out.println(cnt);
System.out.println("End");
} catch (Exception e) {
if (open != null) {
open.rollback();
}
throw e;
}
return cnt;
}

Update table using Hibernate

I am working under a project that is update the data's in MySQL table using Hibernate. Whenever I run the project, the exception is shown as below.
[Batch update returned unexpected row count from update [0]; actual
row count: 0; expected: 1]
Controller
#RequestMapping(value = "/disableEmployeeMaster", method = RequestMethod.POST)
public #ResponseBody void disableEmployee(HttpServletRequest request)
{
EmployeeMaster employeeMaster = new EmployeeMaster();
try
{
String employeeId = request.getParameter("employeeId");
employeeMaster.setIsDel("Y");
mainService.disableEmployee(employeeId , employeeMaster);
}
catch(Exception e)
{
logger.error(e.getMessage());
}
}
Service Implementation
#Override
public void disableEmployee(String Id, EmployeeMaster employeeMaster) {
Session session = null;
Transaction transaction = null;
try
{
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.update(Id, employeeMaster);
transaction.commit();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}
You have't set employeeId to EmployeeMaster class object.
to update any entity needs it's primary key.
You can refer following code :
employeeMaster.setEmployeeId(employeeId);
Controller
#RequestMapping(value = "/disableEmployeeMaster", method = RequestMethod.POST)
public #ResponseBody void disableEmployee(HttpServletRequest request)
{
EmployeeMaster employeeMaster = new EmployeeMaster();
try
{
String employeeId = request.getParameter("employeeId");
employeeMaster.setEmployeeId(employeeId);
employeeMaster.setIsDel("Y");
mainService.disableEmployee(employeeId , employeeMaster);
}
catch(Exception e)
{
logger.error(e.getMessage());
}
}

java.lang.ClassCastException: java.lang.Integer cannot be cast to abc.def.myproject.orm.EmployeeTopMetaData

I am trying to run a SELECT query using Hibernate Criteria API which is defined in the code below. I checked the console and it seems like the
query is running fine. Here is what I am getting in the console for the SQL Query :
Hibernate:
select
this_.VALUE_EMP_ID as y0_
from
EMPLOYEE_TOP_METADATA this_
where
this_.TESTING_ID=?
and this_.COMPANY_EMP_ID=?
But just below the above SQL in the console, I see the error :
java.lang.ClassCastException: java.lang.Integer cannot be cast to abc.def.myproject.orm.EmployeeTopMetaData
at abc.def.myproject.orm.dao.impl.EmpDaoImpl.insertEmployeeDetails(EmployeeDaoImpl.java:50)
And Line #50 is the following line in the below method :
(EmployeeTopMetaData) session.createCriteria(EmployeeTopMetaData.class)
The following method is defined in EmployeeDaoImpl java class.
public boolean insertEmployeeDetails(Employee employee)
{
logger.debug("Starting EmployeeDaoImpl.insert() .....");
Session session = null;
Transaction tx = null;
boolean status = true;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
EmployeeTopMetaData empMetaData =
(EmployeeTopMetaData) session.createCriteria(EmployeeTopMetaData.class) // This is the line #50
.setProjection(Projections.property("valueEmpId"))
.add(Restrictions.eq("testingId", 1234))
.add(Restrictions.eq("company_employee_id", 3345))
.uniqueResult();
if (empMetaData == null || empMetaData. getvalueEmpId() < 1) { throw new Exception("Invalid empMetaData"); }
System.out.println("October 04 EmployeeTopMetaData: ");
System.out.println(empMetaData. getvalueEmpId());
// Some more code to go
session.persist(employee);
tx.commit();
} catch(Exception ex) {
tx.rollback();
ex.printStackTrace();
status = false;
} finally {
session.close();
}
logger.debug("Completed EmployeeDaoImpl.insert() .....");
return status;
}
Here is my Entity Class EmployeeTopMetaData.java :
package abc.def.myproject.orm;
#Entity
#Table(name="EMPLOYEE_TOP_METADATA")
public class EmployeeTopMetaData
{
public int getTestingId() {
return testingId;
}
public void setTestingId(int testingId) {
this.testingId = testingId;
}
public int getCompanyEmpId() {
return company_employee_id;
}
public void setCompanyEmpId(int company_employee_id) {
this.company_employee_id = company_employee_id;
}
public int getvalueEmpId() {
return valueEmpId;
}
public void setvalueEmpId(int valueEmpId) {
this.valueEmpId = valueEmpId;
}
#Id
#Column(name="TESTING_ID")
private int testingId;
#Column(name="COMPANY_EMP_ID")
private int company_employee_id;
#Column(name="VALUE_EMP_ID")
private int valueEmpId;
}
Your query only returns "this_.VALUE_EMP_ID" an int value.
If you want to return a EmployeeTopMetaData, you have to change your query:
Hibernate:
select
this_
from
EMPLOYEE_TOP_METADATA this_
where
this_.TESTING_ID=?
and this_.COMPANY_EMP_ID=?
But I suggest that if you just need VALUE_EMP_ID, it's better to change just the variable.
Integer empMetaData =
(Integer) session.createCriteria(EmployeeTopMetaData.class) // This is the line #50
.setProjection(Projections.property("valueEmpId"))
.add(Restrictions.eq("testingId", 1234))
.add(Restrictions.eq("company_employee_id", 3345))
.uniqueResult();

How to update value at Mongo DB?

I have to write DAO layer for Mongo DB.
I found that this isn't so easy.
My implementation is straightforward:
delete document with the same key => and save updated it again
How possible to do it for List of elements?
For example JSON representation is next:
"airItinerary" : {
"originDestinationOptions" : {
"originDestinationOption" : [ {
"flightSegment" : [ {
"departureAirport" : {
"locationCode" : "DUB",
"codeContext" : "IATA"
},
"arrivalAirport" : {
"locationCode" : "CDG",
"codeContext" : "IATA"
},
Here is my code:
#Override
public void update(MODEL model) {
try {
Field keyField1 = getKeyField(model);
String fieldValue = getKeyFieldValue(keyField1, model);
BasicDBObject query = createQuery(keyField1.getName(), fieldValue);
DBCursor cursor = dbCollection.find(query);
if (cursor.hasNext()) {
DBObject dbObject = getDbObject(model);
dbCollection.update(query, dbObject);
} else {
throw new RuntimeException(String.format("Data status %s isn't presented at %s with value %s", keyField1.getName(), dbCollection.getFullName(), fieldValue));
}
} catch (IOException e) {
Log.getInstance().log(e.getCause());
}
}
private Field getKeyField(MODEL model) {
Field keyField = null;
for (Field field : model.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(KeyField.class)) {
keyField = field;
}
}
if (keyField == null) {
throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
}
return keyField;
}
private String getKeyFieldValue(Field keyField, Object model) {
String result = null;
try {
if(keyField.isAnnotationPresent(KeyField.class)) {
keyField.setAccessible(true);
result = keyField.get(model).toString();
}
if(result == null || result.equals("")) {
throw new NullPointerException();
}
} catch(NullPointerException e) {
throw new RuntimeException("KeyField property is empty");
}catch (Exception e) {
throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
}
return result;
}
private BasicDBObject createQuery(String key, String value) {
BasicDBObject query = new BasicDBObject();
query.put(key, value);
return query;
}
For shure should exist much better way for this result.
I can't find smt at mongo doc for achieving this result.
How to achive the same effect with Mongo tools.
It's allowed to update directly; don't need to find as the first step and this will probably cause inconsistency between update and find operation.
#Override
public void update(MODEL model) {
try {
Field keyField1 = getKeyField(model);
String fieldValue = getKeyFieldValue(keyField1, model);
BasicDBObject query = createQuery(keyField1.getName(), fieldValue);
DBObject dbObject = getDbObject(model);
dbCollection.update(query, dbObject);
/* DBCursor cursor = dbCollection.find(query);
if (cursor.hasNext()) {
DBObject dbObject = getDbObject(model);
dbCollection.update(query, dbObject);
} else {
throw new RuntimeException(String.format("Data status %s isn't presented at %s with value %s", keyField1.getName(), dbCollection.getFullName(), fieldValue));
}
*/
} catch (IOException e) {
Log.getInstance().log(e.getCause());
}
}
private Field getKeyField(MODEL model) {
Field keyField = null;
for (Field field : model.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(KeyField.class)) {
keyField = field;
break; // add a break to jump out quickly.
}
}
if (keyField == null) {
throw new RuntimeException(String.format("Couldn't find KeyField annotation at class '%s'", model.getClass().getName()));
}
return keyField;
}
Also, spring-data-mongodb is a choice to handle these kind of issues.

Categories

Resources