How to put a sum in a String and print it - java

I'm currently working on a receipt of an Java application and I can't seem to get the sum on the screen. When is use the following query I get the sum in PHPMyAdmin but can't seem to find it in Java. I just can't print it because Java tells me all the column names I try are wrong. Does anyone know how to fix this?
If you want more code than this I can provide that but I'm kinda sure there is something faulty in the query and Java can't read it out. Help will be appreciated.
String sql = "SELECT sum((`barorder_drink`.`quantity` * `drink`.`price`)) + sum((`kitchenorder_dish`.`quantity` * `dish`.`price`))"
+ "FROM `barorder`, `barorder_drink`, `drink`, `kitchenorder`, `kitchenorder_dish`, `dish`, `restaurantorder`"
+ "WHERE `barorder`.`restaurantOrderId` = `restaurantorder`.`id`"
+ "AND `kitchenorder`.`restaurantOrderId` = `restaurantorder`.`id`"
+ "AND `barorder_drink`.`barorderId` = `barorder`.`id`"
+ "AND `barorder_drink`.`drinkId` = `drink`.`id`"
+ "AND `kitchenorder_dish`.`kitchenOrderId` = `kitchenorder`.`id`"
+ "AND `kitchenorder_dish`.`dishId` = `dish`.`id`"
+ "AND `restaurantorder`.`id` = '" + ID + "' ;";

Put your sum as a val and get this value like this
String sql = "SELECT sum(myattributes) AS val";
and when you want to get the result
int som = getInt("val");

Maybe when you do ))"
+ "FROM ...
The result is: ))FROM
and it sould be )) FROM

Related

Spring JPA Query is not recognizing Spatial Types

I'm trying to make a native query request through spring JPA Query annotation using Spacial data types.
The query works perfectly when asked to execute through the console or even in the database.
But when he is asked to be used through Spring.
Does anyone know what I'm doing wrong? or there is a better way to achieve the same result (leaving all the calculations DB sided)?
Thank you in advance
This is the query I'm trying to execute. Again, it works through console but fails to execute through spring boot request
#Query(value = "SELECT TOP 1 * FROM Vehicles v " +
"JOIN Bikelots l ON l.BikeLotId = v.BikeLotId " +
"JOIN BikeTypes b ON b.BikeTypeId = l.BikeTypeId " +
"WHERE b.BikeTypeId = ?1 " +
"ORDER BY " +
"Geography::STGeomFromText(v.Point.MakeValid().STAsText(),4326) " +
".STDistance(Geography::STGeomFromText(Geometry::Point(?2,?3,4326).MakeValid().STAsText(),4326)) "
, nativeQuery = true)
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near 'Geography:'.
Im using this dialect in application.properties
spring.jpa.database-platform=org.hibernate.spatial.dialect.sqlserver.SqlServer2008SpatialDialect
The given error was caused because jpa hibernate recognizes the character ":" as a placeholder for an upcoming variable.
By placing the query in a String variable, then adding "\\" before each ":" and assigning the string to the value of #Query, solved the problem. See code for example
String query = "SELECT TOP 1 * FROM Vehicles v " +
"JOIN Bikelots l ON l.BikeLotId = v.BikeLotId " +
"JOIN BikeTypes b ON b.BikeTypeId = l.BikeTypeId " +
"WHERE b.BikeTypeId = ?1 " +
"ORDER BY " +
"Geography\\:\\:STGeomFromText(v.Point.MakeValid().STAsText(),4326) " +
".STDistance(Geography\\:\\:STGeomFromText(Geometry\\:\\:Point(?2,?3,4326).MakeValid().STAsText(),4326)) ";
#Query(value = query, nativeQuery = true)

Hibernate Query, how to use like or = on where clause depend on value passed

I have the following code and query :
String kodeCustomer, kodeDropship, kodeSales, kodePengirim;
kodeCustomer = kodeCustomerTextField.getText().trim();
kodeDropship = kodeDropshipTextField.getText().trim();
kodeSales = kodeSalesTextField.getText().trim();
kodePengirim = pengirimTextField.getText().trim();
... some other code ...
record = session.createQuery("from PenjualanTableDb where"
+ " dtanggalpenjualan >= :dawalParm"
+ " and dtanggalpenjualan < :dakhirParm"
+ " and coalesce(ckodecustomer,'') like :custParm"
+ " and coalesce(ckodedropship,'') like :dropshipParm"
+ " and coalesce(ckodesalesperson,'') like :salesParm"
+ " and coalesce(ckodepengirim,'') like :pengirimParm")
.setParameter("dawalParm", tanggalMulaiTrx)
.setParameter("dakhirParm", tanggalAkhirTrx)
.setParameter("custParm", kodeCustomer + "%")
.setParameter("dropshipParm", kodeDropship + "%")
.setParameter("salesParm", kodeSales + "%")
.setParameter("pengirimParm", kodePengirim + "%")
.list();
how to modify the query so it can give the correct output based on user input.
if textfield empty then the query using like, but if textfield not empty then query using =
Is there an easy way to handle that?
Thanks in advance
I think you should construct the hql query (including parameters) dynamically according to the parameters present instead of using "a like%".
record = session.createQuery("from PenjualanTableDb where"
+ " dtanggalpenjualan >= :dawalParm"
+ " and dtanggalpenjualan < :dakhirParm"
+ " and coalesce(ckodecustomer,'') like '%:custParm%'"
+ " and coalesce(ckodedropship,'') like '%:dropshipParm%'"
+ " and coalesce(ckodesalesperson,'') like '%:salesParm%'"
+ " and coalesce(ckodepengirim,'') like '%:pengirimParm%'")
.setParameter("dawalParm", tanggalMulaiTrx)
.setParameter("dakhirParm", tanggalAkhirTrx)
.setParameter("custParm", kodeCustomer)
.setParameter("dropshipParm", kodeDropship)
.setParameter("salesParm", kodeSales)
.setParameter("pengirimParm", kodePengirim)
.list();

jdbcTemplate.queryForObject returning EmptyResultDataAccessException while normal query runs

I am trying to change a normal query to Parameterized query using jdbcTemplate.queryForObject for avoiding SQL Injection. But the query returns EmptyResultDataAccessException - Incorrect result size: expected 1, actual 0 where the normal query works fine. Below is the normal query where i get the correct result.
StringBuilder builder = new StringBuilder();
String AcctNameBuilder = adhpDetailUtil.getAccName();
builder.append("select * " +
"from gfc.LSI_ELGBLTY " +
"where INSURANCE_ID = '" + request.getInsuranceId() + "' and " +
"SYS_CD = '" + request.getSystemId() + "' and " +
"ACCT_TYPE in (" + AcctNameBuilder.toString() + ")");
Here is the parameterized query that i have created from the above query.
StringBuilder builder = new StringBuilder();
String AcctNameBuilder = adhpDetailUtil.getAccName();
final String QUERY = "select * " + "from gfc.LSI_ELGBLTY " + "where INSURANCE_ID = ? and " + "SYS_CD = ? and " + "ACCT_TYPE in (?)";
Object[] params = new Object[] {
request.getInsuranceId(),request.getSystemId(),AcctNameBuilder};
String ids = jdbcTemplate.queryForObject(QUERY, params, String.class);
builder.append(ids)
In the first case, builder.append contains the exact query while in the second case jdbcTemplate.queryForObject is returning EmptyResultDataAccessException. What am I doing wrong here.
I don't believe you can just append ids for an "IN" clause like that.
The parameter for the "IN" clause is technically an Array. I ran into this a number of years ago and I don't think that this has ever been truly addressed.
If you think about it this is a fairly difficult problem as the query planner for preparing the statement cannot effectively bound the number of parameters.

JPQL Create "Dynamic" Query to execute in repository

Edit-
I'll add the use case to clear up the function of this.
The user will select two dates - a start date and an end date - these are then passed on and used to select the tables (each year has its own table). In one use case where the two given dates lie in the same year it's a simple query on that table alone.
However, if the two dates are different years I will need to join all tables (so 2011-2013 will be three tables connected, to search through) and thus, I want a dynamic fix to this. I know building up a query like below is against security - just thought something similar would work. As the system will get new tables each year I also dont want to have to manually add however many new queries for each case (2011-2016, 2014-2018, 2011-2019.. etc)
I have a question about whether it is possible to create a dynamic query as a String like below and then pass that through to service -> repository, and use that as a query?
for (int i = 0; i < yearCondition; i++) {
if (i == 0) {
query += "SELECT md.Device_ID, l.locationRef, " + reportRunForm.getStartDate() + " as 'From Date', "
+ reportRunForm.getEndDate() + " as 'To Date' "
+ "from mData.meterdata" + iDateStart.substring(0, 4)
+ " join MOL2.meters m on device_ID = m.meterUI "
+ "join MOL2.locations l on m.locationID = l.locationID "
+ "join MOL2.meterreg mr on m.meterID = mr.meterID "
+ "where mr.userID = ?1";
}
query += "UNION SELECT md.Device_ID, l.locationRef, " + reportRunForm.getStartDate() + " as 'From Date', "
+ reportRunForm.getEndDate() + " as 'To Date' "
+ "from mData.meterdata" + (Integer.parseInt(iDateStart.substring(0, 4))+i)
+ " join MOL2.meters m on device_ID = m.meterUI "
+ "join MOL2.locations l on m.locationID = l.locationID "
+ "join MOL2.meterreg mr on m.meterID = mr.meterID "
+ "where mr.userID = ?1";
}
I may have the wrong idea with how this works, and I know I could create and persist a query through entitymanager, but wanted to know whether doing it through the repository would be possible?
My thought was I'd build up the query like above, pass it through to service and then to repository, and bind it as value in #Query annotation but this doesn't seem possible. I'm likely approaching this wrong so any advice would be appreciated.
Thanks.
Edit -
Had a goof. Understand doing it at all like that is stupid, an approach to build up something similar is what I'm looking for that is still secure.
Maybe this annotations before your POJO can help
#org.hibernate.annotations.Entity(dynamicInsert = true)
for example two tables district and constituency ...
Dynamic query
query += "select *from constituency c where 1=1";
if(constituencyNumber!=null)
query +=" and c.constituency_number like '"+constituencyNumber+"%'";
query += " group by c.district_id";
OR
select *from constituency c where (c.constituency_number is null or c.constituency_number like '1%') group by c.district_id;

JDBC error with PreparedStatement

I'm trying to write a small function that gets an id u (integer), and returns the number of friends u have with distance <=3 (the friends information is stored in the table Likes: Likes(uid1, uid2) means: uid1 likes uid2).
I wrote this simple query:
String likesDistance =
"SELECT uid2 " + //DISTANCE = 1
"FROM Likes " +
"WHERE uid1 = ? " +
"UNION " +
"SELECT L2.uid2 " + //DISTANCE = 2
"FROM Likes L1, Likes L2 " +
"WHERE L1.uid1 = ? and L1.uid2 = L2.uid1 " +
"UNION "+
"SELECT L3.uid2 " + //DISTANCE = 3
"FROM Likes L1, Likes L2 , Likes L3 " +
"WHERE L1.uid1 = ? and L1.uid2 = L2.uid1 and L2.uid2 = L3.uid1 ";
Then, I do the following:
PreparedStatement pstmt2 = con.prepareStatement(likesDistance);
pstmt1.setInt(1, u);
pstmt1.setInt(2, u);
System.out.println("2");
pstmt1.setInt(3, u);
System.out.println("3");
pstmt1.setInt(4, u);
pstmt1.setInt(5, u);
Where u, as mention before, is an integer passed to the function.
All this code is within a 'try' block. When I try to run it, it prints the first printout ("2"), but not the second one ("3"), and I get the following exception message:
The column index is out of range: 3, number of columns: 2.
Why is it like this, and how can I change it to work as I want?
Thanks a lot.
Copy and paste? Guess you wanted to set parameters for statement 2.
Your prepared statement is pstmt2.
You are setting properties on pstmt1.
Try setting the properties on pstmt2 and it should work.
Though you set properties on pstmt2 you get exception as there are only three placeholders in the statement and you are setting for five placeholders.

Categories