How to get latest 5 results from MySQL database using Spring,Hibernate - java

I need some help to fix my issue. I'm having a REST webservices project with Spring and Hibernate. By executing the POST call in POSTMAN,I've inserted some details into MySQL database. So, now i need to get latest 4(which means last 4) from the database table using GET
---id--------|----testname---|----testmethod----|---groupname---|-result----
So, these above mentioned are the columns of my database table. so i need to get last 4 results based on column groupname. So, i need to search by groupnameand id. The values of groupname will be like [Test]. So, can anyone tell is there any way to get those details through GET call.

If you want to retrieve some specific number of rows from database using hibernate then you can do something like this
Criteria cr = session.createCriteria(YourClass.class);
cr.setFirstResult(1);
cr.setMaxResults(4);
List results = cr.list();
The above code will retrieve first 4 rows from your DB.
If you want to retrieve last 4 rows then you have to somehow count the number of rows then use code like this
Criteria cr = session.createCriteria(YourClass.class);
cr.setFirstResult(count-4);
cr.setMaxResults(count);
List results = cr.list();
it will give you last 4 rows from your DB.
if you want to use HQL then you can do something like this
Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);

Related

SQL/JPA want to select data for a list of ids filtering by a specific timestamp range for each id

I have a table with some data, there are record id, userIds, timestamp and data columns. Receive from the client a list of userIds, initially, I just had to fetch data by the same timestamp range for all useIds, just using userId IN (list). However, now I'm required to get data by different timestamp ranges for each userId, let's say userID 1 needs data from 1643580000000 to 1646431200000 and userId 2 from 1626418800000 to 1647500400000 (utcTimestamp in mills).
Most probably I'll receive a list of [userId, startTime, endTime], so, I was considering to loop the main query for each userId with its respective timestamp range (I've seen it's a bad idea due to performance, but if I have to, I have to), but I also found out about cursors (not much experience here).
I wanted to know if it's possible to get what I want without loops or cursors, and if not, best way with each one.
Thanks in advance!
Notes: using MariaDB. SQL query will be used as nativeQuery in a Java service repository.
You can run a query laike this.
Of course you have to add for every user his own time range
SELECT * FROM mytable
WHERE (userID = 1 AND `timestamp` BETWEEN 1643580000000 AND 1646431200000)
OR (userId = 2 AND `timestamp`BETWEEN 1626418800000 AND 1647500400000)
If you have a lot of rows and not that many id to process, you can do it with
SELECT * FROM mytable
WHERE (userID = 1 AND `timestamp` BETWEEN 1643580000000 AND 1646431200000)
UNION
SELECT * FROM mytable
WHERE (userId = 2 AND `timestamp`BETWEEN 1626418800000 AND 1647500400000)
Here also you need to add for every id another UNION

create with params don't insert new Rows to the database table

im trying to use the createwithparm method programmatically in adf
to insert new record in the database but it doesnt works
i have db table with 2 generated values with before insert triggers
and i will pass 2 values
and this is my code
OperationBinding operation = ADFUtils.findOperation("CreateWithParams");
Object result = operation.execute();
and from the edit action binding I've referenced the 2 values i want to pass
{pageFlowScope.userBean.investorNumber}
{pageFlowScope.userBean.tempCode}
but nothing is inserted in the database
and there is nothing in the log
Given that you said "nothing is inserted into the database", I have to ask: Do you understand how ADF BC(EO, VO, AM) works? When you submit a page, for example with createwithparam, it updates the EO and VOs in the ADF BC middle tier model, in memory. Nothing is written to the database. You must issue a COMMIT through the enclosing Application Module to get the data written to the db.
This might help.

Update Query using Temporary Table is taking a lot of time in Postgres

I have a Main Table named REF_SERVICE_OFFERING where-in I already have 3 Million+ data. Now, I wanted to update the 3M records in Java based on some specific condition.
We decided to create a temporary table (where-in the records within will be used to Update the Main Table) and using the below query to Update the Main Table. The temporary table will hold more than 200k records :
UPDATE REF_SERVICE_OFFERING SET
PART_PRICE_BILL_TYPE= TEMP.PART_PRICE_BILL_TYPE,
part_price_unit_type=TEMP.part_price_unit_type,
part_price_allowed_units=TEMP.part_price_allowed_units,
part_price_discount=TEMP.part_price_discount,
part_price_source_id=TEMP.part_price_source_id
FROM REF_SERVICE_OFFERING RSO JOIN ref_offer_temp1 TEMP
ON TEMP.RECORD_NUM = RSO.RECORD_NUM
AND TEMP.SO_NAME = RSO.SO_NAME
AND TEMP.SERVICE_CASE_TYPE = RSO.SERVICE_CASE_TYPE
AND TEMP.WORK_ORDER_TYPE = RSO.WORK_ORDER_TYPE
WHERE (RSO.PART_PRICE_BILL_TYPE IS NOT NULL OR TRIM(RSO.PART_PRICE_BILL_TYPE) NOT LIKE '')
AND (RSO.PART_PRICE_EXCP_SOURCE_ID IS NOT NULL OR TRIM(RSO.PART_PRICE_EXCP_SOURCE_ID) NOT LIKE '')
Our database is Postgres 9.6. But this update is taking a lot of time and never edning. We also tried dumping only 10k records in the temporary table which will be used to update 4L records.
We tried doing EXPLAIN command and couldnt figure out the reason why.
Any help would be really appreciated.

How to add custom column name Spring Data JPA? [duplicate]

This question already has an answer here:
Column name as a parameter to Spring Data JPA Query
(1 answer)
Closed 6 years ago.
I have lots of column in my DB and don't want to write custom queries for all of them so consider the below method runs for every column name dynamicaly which i give as column_name. Is something like this possible or are there any other way to do that?
#Query("select #column_name from Item Where #column_name like %?2% ")
List<Item> getUniqueColumn(String column_name,String column_text);
By the way in spring documantation this case not mentioned.
You can only pass values that you are expecting as parameters to your HQL queries. You can't pass column or table names.
Hibernate is basically working here with a PreparedStatement, and a statement cannot be prepared where the table / columns being queried for are not known yet.
You would have to write some String replacement logic or build your query with the Criteria API
List<Object> getUniqueColumn(String column_name,String column_text){
StringBuilder query = new StringBuilder();
query.append("select #column_name ");
query.append("from Item ");
query.append("where #column_name like %?1%");
query = query.toString("#column_name", column_name);
session.createQuery(query).setString(1, column_text).list();
}
Also remember that what you are doing here is a projection and you will not get a List of Item but a List of Objects.

How to use update hibernate query using setMaxResults?

I hope it is the appropriate section, I have a problem with this code
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("update database set floop= :ctrl1" +" where ctrl= :ctrl2 ").setMaxResults(2);
query.setMaxResults(2);
query.setParameter("ctrl1",3);
query.setParameter("ctrl2", 5);
I ask through setMaxResults(2) to do the update only on the first two and he makes the update of all records as I do what is wrong?? thanks for any help
I thought to use session.createSQLQuery, but I do not know how to do.
This answer is posting delay but it can be helpful for others user who is looking update number of rows in DB with limit using HQL
Unfortunatly setMaxResults() do not work update and delete hibernate
query. It works only select criteria.
As per HQL there is no specific solution is available and you want to update rows with number of limit then follow below steps
Write a HQL to select all rows with condition or range with
setMaxResults. It will return you a List object with limit.
Then update the specific property (Property you want to update) and
store Objects of these rows again by session.update() method.
I'm assuming tablename with map Database class and there are two variable ctrl and floop with getter and setter(as per your question)
List<Database> list = new ArrayList<>();
Transaction transaction = session.beginTransaction();
//Fetching record with limit 2 using setMaxResults()
int setlimit = 2;
String hql_query = "from Database where ctrl = :ctrl2";
Query select_query = session.createQuery(hql_query).setMaxResults(setlimit);
select_query.setParameter("ctrl2", 5);
list = select_query.list();
//iterating list and setting new value to particuler column or property
int result;
if (list != null) {
for (Database element : list) {
element.setFloop(ctrl1);
//Here is updating data in database
session.update(element);
}
result = list.size();
} else {
result = 0;
}
System.out.println("Rows affected: " + result);
transaction.commit();
setMaxResults limits the number of results which are returned by the query, not the number of affected rows.
When you only want to update a limited set of rows, you should specify these rows within the where condition. Setting a hard limit on the number of updated rows wouldn't make much sense, because there would be no way to tell which rows would be updated.
query.setMaxResults(2); will be used for selection queries and will be ignored for insertion/updation. If you use it for selection queries, then you will get 2 records in result.
setMaxResults only applies to select. For your problem I would perform a select query and then use the query.setMaxResults(2), this will return a list of max 2 elements. Then loop the list returned and use session.update for the one or two elements returned.
I can see a number of perfectly valid use-cases where you want to update only a limited number of rows and as other have already answered, the Hibernate Query cannot deal with this so you need to resort to native SQL.
You don't specify in the question which type of database you are using so this answer will only apply to MySql:
Transaction transaction = session.beginTransaction();
Query query = session.createSQLQuery("UPDATE database SET floop= :ctrl1 WHERE ctrl= :ctrl2 LIMIT :max");
query.setParameter("ctrl1",3);
query.setParameter("ctrl2", 5);
query.setParameter("max", 2);
Please note that the sql query above needs to use the native table and column names and not the ones in your ORM model.

Categories

Resources