Equivalent of `set #variable = 0` in spring data jpa - java

I am trying to execute following queries in one go on MySQL through spring data jpa.
SET #i := 0;
UPDATE tv_episode te SET te.display_episode_no= #i:=#i+1 WHERE te.tv_season_id=season ORDER BY broadcast_date;
I tried finding out a solution for this on StackOverflow, but couldn't find any.
What is the equivalent of SET #i := 0; in spring-data-jpa? Is there a way I can execute the statement in #Modifying & #Query annotated method?

You can run native queries by adding nativeQuery = true to #Query :
#Modifying
#Query(value = "SET #i := 0;\n" +
"UPDATE tv_episode te SET te.display_episode_no= #i:=#i+1 WHERE te.tv_season_id = :season", nativeQuery = true)
int updateUserSetStatusForName(#Param("season") Integer season);
And If you don't want to use native query you can pass parameters like this:
#Modifying
#Query("update TvEpisode te set te.displayEpisodeNo = :epiodeNo where te.tvSeasonId = :season")
int updateUserSetStatusForName(#Param("epiodeNo") Integer epiodeNo,
#Param("season") Integer season);

Related

Parameter not bound in Hibernate Query

I tried to make a query withSpring data for updating an entry by id and I tried a lot options but still I can't get rid of this:
Named parameter not bound : table.eventDate
#Modifying
#Query(value = "update Table_name u set u.id = :table.id, u.event_date = :table.eventDate, u.client_id = :table.clientId, u.status = :table.status, u.status_date = :table.statusDate, u.creation_date = :table.creationDate, u.last_update_date = :table.lastUpdateDate where u.id = :table.id",
nativeQuery = true)
void updateEntity(#Param("table") Table table);
How should I write the query in order to get rid of this?
I tried a lot of posibilities online to write the query but nothing worked.
Correct native query statement:
#Modifying
#Query(value = "update Table_name u set u.id = :table.id, u.event_date = :table.event_date, u.client_id = :table.client_id, u.status = :table.status, u.status_date = :table.status_date, u.creation_date = :table.creation_date, u.last_update_date = :table.last_update_date where u.id = :table.id",
nativeQuery = true)
void updateEntity(#Param("table") Table table);
Since you're using a native query instead of a JPQL-Query, you have to write :table.event_date instead of :table.eventDate. Same counts for example :table.clientId, it has to be :table.client_id.
Hope it'll work!
Native Queries: Always snake_case instead of camelCase, unless your column names are in camelCase, but I doubt that. :)

Why is the first Query working and the second not? (Spring application JPA)

I have two Query's that I want to use in a Spring project (using JPA). The first one gets an account and this works correctly. For the second one I want it to be able to update the 'disabled' field in the database. The codes look like this:
// This is the first Query (works correctly)
#Query(value = "SELECT * FROM accounts WHERE email = ?1", nativeQuery = true)
Account findByEmailAddress(String emailAddress);
// This is the second Query (doesn't work)
#Modifying
#Query(value = "UPDATE accounts SET disabled = 1 WHERE email= ?1 ", nativeQuery = true)
int disableAccountByEmail(String emailAddress);
I did read somewhere I needed to add #Modifying and this will return an int or void. But when I try to test if it works I get a TransactionRequiredException error that says: Executing an update/delete query
Try using the below for update query
#Transactional
#Modifying(clearAutomatically = true)

Select Top 1 records from MS SQL using Spring Data JPA

I am using the below #Query annotation to get the first few record from MS-SQL. It's showing error saying "< operator > or AS expected..."
#Query("SELECT Top 1 * FROM NEVS010_VEH_ACTV_COMMAND C WHERE C.EVS014_VIN = :vin ORDER BY C.EVS010_CREATE_S DESC")
CommandStatus findCommandStatusByVinOrderByCreatedTimestampDesc(#Param("vin") String vin);
You can also use findFirst and findTop as mentioned in the Docs:
findFirstByVinOrderByCreatedTimestampDesc(String vin)
Since the query is SQL (and not JPQL) one needs to set nativeQuery = true in the annotation:
#Query(nativeQuery = true, value = "SELECT Top 1 * FROM NEVS010_VEH_ACTV_COMMAND C WHERE C.EVS014_VIN = :vin ORDER BY C.EVS010_CREATE_S DESC")
CommandStatus findCommandStatusByVinOrderByCreatedTimestampDesc(#Param("vin") String vin);
For custom Queries without using nativeQuery, the field ROWNUM can be used.
Ex (in Kotlin but the same idea works in Java):
#Query("""
SELECT a
FROM Account a
WHERE a.bla = :ble
AND ROWNUM = 1
ORDER BY a.modifiedDate DESC
""")
fun findWhatever(#Param("ble") someParam: String)
I haven't found that on any doc so far. I just tested and it worked for Oracle, MySQL and H2

org.postgresql.util.PSQLException: No results were returned by the query [duplicate]

I am trying to insert a data into a table. After executing the query i am getting an exception stating
org.postgresql.util.PSQLException: No results were returned by the query.
org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:284)
The data is getting inserted successfully, but i have no idea why i am getting this exception ??
Use
executeUpdate
instead of
executeQuery
if no data will be returned (i.e. a non-SELECT operation).
Please use #Modifying annotation over the #Query annotation.
#Modifying
#Query(value = "UPDATE Users set coins_balance = coins_balance + :coinsToAddOrRemove where user_id = :user_id", nativeQuery = true)
int updateCoinsBalance(#Param("user_id") Long userId, #Param("coinsToAddOrRemove") Integer coinsToAddOrRemove);
The same is true for any DML query (i.e. DELETE, UPDATE or INSERT)
Using #Modifying and #Transaction fixed me
The problem that brought me to this question was a bit different - I was getting this error when deleting rows using an interface-based Spring JPA Repository. The cause was that my method signature was supposed to return some results:
#Modifying
#Query(value = "DELETE FROM table t WHERE t.some_id IN (:someIds)", nativeQuery = true)
List<Long> deleteBySomeIdIn(#Param("someIds") Collection<Long> someIds);
Changing the return type to void resolved the issue:
#Modifying
#Query(value = "DELETE FROM table t WHERE t.some_id IN (:someIds)", nativeQuery = true)
void deleteBySomeIdIn(#Param("someIds") Collection<Long> someIds);
If you want last generated id, you can use this code after using executeUpdate() method
int update = statement.executeUpdate()
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
I have solved this Problem using addBatch and executeBatch as following:
statement.addBatch("DELETE FROM public.session_event WHERE id = " + entry.getKey());
statement.executeBatch();

Pass the dynamically created query (according to condition) in #Query annotation

I am using the #Query annotation to execute the query in spring repository.
But I want to change the some part or make a new query according to the condition and pass in the #Query("pass here the query according to condition")
This is my query
#Query("SELECT ds.symptom FROM DoctorSymptomsModel ds where ds.doctorId = :doctorId and ds.isMostUsed = :isMostUsed)
If some condition satisfy then concat the "ORDER BY createdDate" part in query.
Or
Can I make the variable and set the query in that variable and set like that
String query = SELECT ds.symptom FROM DoctorSymptomsModel ds where
ds.doctorId = :doctorId and ds.isMostUsed = :isMostUsed
if(result){
query = SELECT ds.symptom FROM DoctorSymptomsModel ds where ds.doctorId =
:doctorId and ds.isMostUsed = :isMostUsed ORDER BY createdDate
}
//pass the query variable here
#Query(query)
List<String> findDoctorSymptomsModelList(#Param("doctorId") long doctorId,
#Param("isMostUsed") boolean isMostUsed);
To make a dynamic query, you should think about CriteriaQuery. Take a look at this link for brief introduction.

Categories