Convert H2 sql query to JPQL - spring-data-jpa

I'm using H2 database in developpement, i wrote a native query, that supports only H2. I want now to convert it to JPQL, so i can use it in production mode.
Inside the query i'm using the DATE_ADD function, which adds a value from the database to the current date, i have tried to search the equivalent for JPQL, but i wasn't successful.
#Modifying
#Transactional
#Query(
value = "UPDATE ORDER_TABLE O SET O.STATE='CANCELED' WHERE O.STATE='PENDING' AND DATEADD('HOUR',SELECT P.VALUE FROM PARAMETER P WHERE P.NAME ='PENDING_ORDER_TTL' , O.CREATED_AT) < NOW()",
nativeQuery = true)
void updatePendingOrder();

You need to calculate the Date in Java:
#Query(value = "UPDATE Order o SET o.state='CANCELED'" +
" WHERE o.state='PENDING' AND o.createdAt < :cutOff")
#Modifying
//Date/LocalDate/LocalDateTime or whatever
public void updateOrders(#Param("cutOff") Date cutOff)

Related

Postgresql jsonb operators not working with spring data jpa

I am trying to use postgresql jsonb operators with spring data jpa query as:
#Query(value="SELECT * from Employee e WHERE e.details #> '{\"province\":{\"city\":{\"town\": \":town\"}}, \"hobbies\": [\":hobby\"]}'",nativeQuery = true)
town and hobby are inputs.
There is no error but no result is returned, though records are there which meets the criteria
It seems parameter binding is not working.
What can be the solution?
Here, :town and :hobby is inside ''(single quote) means string literal, so parameter can't be replaced. You can use || to concat as string so that parameters are not inside in '' and can be replaced.
#Query(value="SELECT * from Employee e WHERE e.details #> ''||'{\"province\":{\"city\":{\"town\": \"' || :town || '\"}}, \"hobbies\": [\"' || :hobby || '\"]}'||'' ", nativeQuery = true)

JPA Criteria orderBy: unexpected AST node

I have the following criteria query, which retrieves some fields from Anfrage and Sparte entities and also the translated string for the sparte.i18nKey.
This works as expected if I dont use orderBy.
Now I have the requirement to sort by the translated string for sparte.i18nKey and using the orderBy as shown below, results in QuerySyntaxException: unexpected AST node
So the problem must be the subselect in the orderBy clause!
select distinct new
my.domain.model.dto.AnfrageDTO(
anfrage0.id,
anfrage0.name,
anfrage0.sparte.id,
anfrage0.sparte.i18nKey,
-- retrieve translated string for sparte.i18nKey
(select rb0.value from at.luxbau.mis2.domain.model.ResourceBundleEntity as rb0
where (anfrage0.sparte.i18nKey = rb0.key) and (rb0.language = 'de'))
)
from my.domain.model.impl.Anfrage as anfrage0
left join anfrage0.sparte as sparte
order by (
-- sort by translated string for sparte.i18nKey
select rb1.value
from my.domain.model.ResourceBundleEntity as rb1
where (anfrage0.sparte.i18nKey = rb1.key) and (rb1.language = 'de')
) asc
My Java code looks like this:
private List<AnfrageDTO> getAnfragen() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<AnfrageDTO> query = cb.createQuery(AnfrageDTO.class);
Root<Anfrage> anfrage = query.from(Anfrage.class);
anfrage.join(Anfrage_.sparte, JoinType.LEFT);
query.select(cb.construct(AnfrageDTO.class,
anfrage.get(Anfrage_.id),
anfrage.get(Anfrage_.name),
anfrage.get(Anfrage_.sparte).get(Sparte_.id),
anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey),
// create subquery for translated sparte.i18nKey
createResourceBundleSubQuery(cb, query, anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey)).getSelection()));
TypedQuery<AnfrageDTO> tq = entityManager
.createQuery(query)
// use subquery to sort by translated sparte.i18nKey
.orderBy(cb.asc(createResourceBundleSubQuery(cb, query, anfrage.get(Anfrage_.sparte).get(Sparte_.i18nKey))));
tq.setMaxResults(10);
List<AnfrageDTO> anfragen = tq.getResultList();
return anfragen;
}
public Subquery<String> createResourceBundleSubQuery(CriteriaBuilder cb, CriteriaQuery<?> query, <String> expr) {
Subquery<String> subquery = query.subquery(String.class);
Root<ResourceBundleEntity> rb = subquery.from(ResourceBundleEntity.class);
subquery
.select(rb.get(ResourceBundleEntity_.value))
.where(cb.and(
cb.equal(expr, rb.get(ResourceBundleEntity_.key)),
cb.equal(rb.get(ResourceBundleEntity_.language), "de")));
return subquery;
}
Using a native SQL query with subselect in orderBy works also as expected.
select distinct
anfrage0_.id,
anfrage0_.name,
anfrage0_.sparte_id,
sparte4_.i18n_key,
(select rb3.i18n_value from resource_bundle rb3 where rb3.language_code = 'de' and rb3.i18n_key = sparte4_.i18n_key) as sparte_i18n_value
from
mis2.anfrage anfrage0_
left outer join mis2.sparte sparte4_ on anfrage0_.sparte_id = sparte4_.id
order by (
select rb.i18n_value
from mis2.resource_bundle rb
where sparte4_.i18n_key = rb.i18n_key and rb.language_code = 'de'
) asc
Also using an alias in the native SQL query works also as expected.
select distinct
anfrage0_.id,
anfrage0_.name,
anfrage0_.sparte_id,
sparte4_.i18n_key,
(select rb3.i18n_value from resource_bundle rb3 where rb3.language_code = 'de' and rb3.i18n_key = sparte4_.i18n_key) as sparte_i18n_value
from
mis2.anfrage anfrage0_
left outer join mis2.sparte sparte4_ on anfrage0_.sparte_id = sparte4_.id
order by sparte_i18n_value
asc
It would be great if JPA Criteria API would support using an alias in orderBy clause!
Any hints welcome - Thank you!
My environment is WildFly 11 and PostgreSQL 9.6.
JPA doesn't support passing parameter in order by clause, your problem has been asked before: Hibernate Named Query Order By parameter

how to use date_part in hibernate query?

String q = "select id from Calendar c " +
"where c.isActive = 1 and " +
"date_part('dow', '2017-09-19 13:23:23'::date) = c.frequencyValue)";
Query query = em.createQuery(q);
List results = query.getResultList();
If I include ::date, hibernate would complain because : conflicts with parameter, but if I don't, postgres will complain. Could not choose a best candidate function. You might need to add explicit type casts. What can I do?
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-expressions
as specified extract function should work if the underlying db supports them so:
extract(dow from date '2017-09-19 13:23:23');
should works

OpenJPA String as date attribute

I have a Query to parse on JPA , some errors have happened . I want a right way to make this.
Original:
Query q = this.em.createQuery("SELECT e FROM Entity e WHERE e.codigo = :codigo ORDER BY e.data ASC");
My solution but doesn't work:
Query q = this.em.createQuery("SELECT e FROM Entity e WHERE e.codigo = :codigo ORDER BY to_date(e.data,'DD/MM/YYYY') ASC");
where e.data is a String like "01/01/2014"
Solved
I´d replaced it with a nativeQuery.
Then a had be able to use Oracle Date Function

TemporalTipe.Time parameter in jpql

I want filter by Time in jpql but I think that I´m not doing well.
SELECT e FROM Pedido e WHERE e.fechaEntrega = :fechaInicio AND e.horaEntrega < :horaEntrega and que.setParameter("horaEntrega", horaEntrega, TemporalType.TIME); but when i see return this not filter by horaEntrega. I'm using eclipselink 2.5 any idea???
I tryed use SELECT e FROM Pedido e WHERE e.fechaEntrega = :fechaInicio AND CAST(e.horaEntrega AS TIMESTAMP) < :horaEntrega and doesn´t work and if i try cast to Time says me that expected NUMBER and got DATE
It´s weird when I write SELECT in sql im using cast(cast(etretst as timestamp) as time) < '08:00:00' and this works fine. And when I write this say me that expected TIME not a DATE
I resolved SELECT SELECT e FROM Pedido e WHERE e.fechaPedido = :fechaInicio AND CAST(CAST(e.horaPedido AS TIMESTAMP) AS TIME) < :horaZona and parameter is que.setParameter("horaZona", new Time(horaPedido.getTime()).toString());