JPA setting parameter wrongly - java

Query:
SELECT m.name,SUM(EXTRACT(EPOCH FROM(p.end- p.begin)) / 60)) FROM Production p
inner join p.machine m
WHERE m = ?1
AND p.begin BETWEEN ?2 AND ?3
AND p.begin BETWEEN ?4 AND ?5
group by m.name;
Parameters:
Query query = getEntityManager().createQuery(jpql)
.setParameter(1, machie)
.setParameter(2, Timestamp.from(begin.toInstant()), TemporalType.TIMESTAMP)
.setParameter(3, Timestamp.from(end.toInstant()), TemporalType.TIMESTAMP)
.setParameter(4, Timestamp.from(beginHour.toInstant()), TemporalType.TIME)
.setParameter(5, Timestamp.from(endHour.toInstant()), TemporalType.TIME);
The Exception:
Caused by: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type timestamp: "05:00:00-03"
How do I make the parameter be set correctly? It is setting "05:00:00-03" when the correct would be "05:00:00".

Related

Spring pagination exception

I'm using Spring Data JPA. Could someone say, how to fix this error: "java.sql.SQLSyntaxErrorException: Unknown column 's' in 'field list'" while executing this simple request. "s" is alias for session table. I shortened the query.
#Query(value =
"SELECT l.name as lName, c.id as clientId, c.name as clientName, s.id as sessionId, a.ss_id as ssId, " +
"u.first_name as firstName, u.last_name as lastName, s.start_date as startDate, s.end_date as endDate, " +
"sc.version as version " +
"FROM session as s " +
"join scenario sc on sc.id = s.scenario_id " +
.........
"left join client c on c.id = p.client_id " +
"WHERE s.status = 'COMPLETED' " +
"and (s.record_rejected IS NULL OR s.record_rejected = 0) " +
"and sfe.id IS NULL " +
.........
"and s.end_date between :startDate and :endDate",
nativeQuery = true)
Page<DataItem> findData(Pageable pageable, #Param("startDate") LocalDateTime startDate, #Param("endDate") LocalDateTime endDate, .......);
}
In log I see the reason of the problem, after my main request spring data executes count request for Pageable object and this request starts with: select count(s) FROM session as s, but this is wrong. You can see it below in the text:
Hibernate: SELECT l.name as lName....
Hibernate: select count(s) FROM session as s ....
2022-02-24 22:10:51.864 WARN [app,363fdd7d5edaa51c,175b13cac216908e,true] 1 --- [nio-8082-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2022-02-24 22:10:51.864 ERROR [app,363fdd7d5edaa51c,175b13cac216908e,true] 1 --- [nio-8082-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 's' in 'field list'
on the second line framework tries execute select count(s), but s is an alias for the table session. And this happens only when required size is less than totalElements, if not, then request is success.
DataItem is an interface projection.
What's wrong? Why framework tries to use table alias inside count() function?
I've tried to use countQuery argument in #Query annotation, but it didn't help.

'Could not extract ResultSet' error when using nativeQuery in JPA

I'm using JPARepository in SpringBoot and using the #Query annotation but I get an error
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
When using the nativeQuery=true
This is my function:
#Query(value = "select * from table1 where status = ?1 and time <= ?2 LIMIT 2", nativeQuery = true)
List<MyModel> findScheduledSmsMessages(Status status, LocalDateTime time);
I added the following code above my query and
#Modifying
#Transactional
Like this :
#Modifying
#Transactional
#Query(value = "DELETE FROM played_sheet WHERE user_id = ?1 AND sheet_music_id = ?2", nativeQuery = true)
void deleteByUserIdAndSheetMusicId(Integer userId,Integer sheetMusicId);

org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias [id] during auto-discovery

#Query(value = "select * from associate_mapping inner join station s on associate_mapping.station_id = s.id \r\n"
+ "inner join shift sh on associate_mapping.shift_id = sh.id inner join line l on l.id = s.line_id \r\n"
+ "where 1=1 and l.line_name = ?1 and sh.shift_name = ?2 ", nativeQuery = true)
List<AssociateMapping> getOperatorRequirementByLineAndShift(String selectedLine, String selectedShift);
and error are
Caused by: org.hibernate.loader.custom.NonUniqueDiscoveredSqlAliasException: Encountered a duplicated sql alias [id] during auto-discovery of a native-sql query
at org.hibernate.loader.custom.CustomLoader.validateAliases(CustomLoader.java:508) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]

Use postgres function timestamp in JpaRepository

I try to group by date only, column active_to is timestamp so it has time also. This query works in pgAdmin but JpaRepository seems to have problem even if it is native query. How can I modify this query to work using JpaRepository?
#Query(value = "SELECT o.active_to::timestamp::date, count(o) as sum from work_order o group by o.active_to::timestamp::date order by o.active_to::timestamp::date asc limit 7", nativeQuery = true)
I get this error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
Position: 19
You cannot use : because this is the character that starts a named parameter.
You have to use cast.
#Query(value = "SELECT cast(cast(o.active_to as timestamp) as date), count(o) as sum " +
"from work_order o group by cast(cast(o.active_to as timestamp) as date) " +
"order by cast(cast(o.active_to as timestamp) as date) asc limit 7",
nativeQuery = true)
Cast and :: are similar. Read more about here:
https://www.postgresql.org/docs/current/sql-expressions.html#SQL-SYNTAX-TYPE-CASTS

Delete From JPA Query with Inner Join

I keep getting errors when trying to get this SQL correct for a JPA repository delete. What is the correct syntax?
#Query("delete * from TS t inner join TSC c ON t.tenantId = c.id where t.id= ?1 AND c.endDate < ?2")
void deleteTSWithExpiredDate(Long id, Date date);
Caused by: java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
Another
#Query("delete t.* from TS t inner join TSC c ON t.tenantId = c.id where t.id= ?1 AND c.endDate < ?2")
void deleteTSWithExpiredDate(Long id, Date date);
expecting IDENT, found '*' near line 1, column 10 [delete t.*
Another
#Query("delete t from TS t inner join TSC c ON t.tenantId = c.id where t.id= ?1 AND c.endDate < ?2")
void deleteTSWithExpiredDate(Long id, Date date);
unexpected token: from near line 1, column 10 [delete t
The syntax for bulk delete is:
Query q = session.createQuery("delete Entity where id = :idParam");
// set params here
q.executeUpdate();
However from Hibernate documentation, no joins can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the sub-queries themselves can contain joins.

Categories