JPA Native Query delete in - jpa

I try to delete a list of rows from a table using this Native Query:
#NamedNativeQuery(name="WebGroup.DeleteIn",
query="DELETE FROM WebGroup WHERE
WebGroup.GROUP_ID IN (:IDsList)"
getEm().createNamedQuery("WebGroup.DeleteIn")
.setParameter("IDsList", groupToDeleteIDs)
.executeUpdate();
and this is the SQL that MySQL executes:
DELETE FROM WebGroup WHERE WebGroup.GROUP_ID IN (:IDsList)
SO, JPA doesn't replace the variable IDsList...
Some one could help me please?

One way that works is if you not use the id value like you tried, but instead use the entity and let JPA handle the identification of it like this:
HashSet<Transaction> transactions = new HashSet<Transaction>();
...
entityManager.createQuery(
"DELETE FROM Transaction e WHERE e IN (:transactions)").
setParameter("transactions", new ArrayList<Transaction>(
transactions)).executeUpdate();
Hope it helps you in the right direction.

native queries do not support collection expansion neither named parameters.
you should write:
#NamedNativeQuery(name="WebGroup.DeleteIn", query="DELETE FROM WebGroup WHERE WebGroup.GROUP_ID IN (?,?,?,?)"
Query query = getEm().createNamedQuery("WebGroup.DeleteIn");
for(int i = 0; i < 4; i++) query.setParameter(i + 1, groupToDeleteIDs.get(i));
query.executeUpdate();
but it is horrible
on eclipselink + mysql this one works:
#NamedNativeQuery(name="WebGroup.DeleteIn", query="DELETE FROM WebGroup WHERE WebGroup.GROUP_ID IN (?)"
Query query = getEm().createNamedQuery("WebGroup.DeleteIn");
query.setParameter(1, StringUtils.join(groupToDeleteIDs, ",");
query.executeUpdate();
however it is not very nice...
but there isn't any other solution using a named query.

Related

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

JPA Query with GROUP BY, HAVING and COUNT

So the query below is probably not the most efficient, buy still, I am wondering why it is returning no result, even though the SQL counterpart does. There is no error, I am just getting no result. Is it maybe not the correct equivalent for the query I wrote in MySQL?
This is the JPA JPQL.
Query query = em.createQuery("SELECT sub FROM Subscription sub WHERE "
+ "sub.isSuspended = 0 AND "
+ "(SELECT i FROM Invoice i WHERE i.dateDue < CURRENT_DATE AND i.datePaid IS NULL "
+ "GROUP BY i HAVING COUNT(i.idInvoice) > 2) MEMBER OF sub.invoices");
And this is the SQL from MySQL.
SELECT * from subscription
WHERE subscription.is_suspended = 0 AND id_subscription IN
(SELECT id_subscription FROM invoice
WHERE date_due < CURDATE() AND date_paid IS NULL
GROUP BY id_subscription
HAVING COUNT(*) > 2)
The two queries are not the same. To use the actual query use the NativeQuery createNativeQuery() instead of Query.
In your case the JPA version seems to have syntax errors.
After the AND you are missing the IN operator.
In the nested query you are selecting i instead of something like i.idInvoice
The JPA query should look like
SELECT sub FROM Subscription sub
WHERE sub.isSuspended = 0
AND sub.idSubscription IN
(SELECT i.idInvoice
FROM Invoice i
WHERE i.dateDue < CURRENT_DATE AND i.datePaid IS NULL
GROUP BY i.idInvoice
HAVING COUNT(i.idInvoice) > 2);

How to implement raw sql query in Tastypie

I am trying to do this simple query, but it does not work. Thanks.
SELECT * FROM TSimple where (start_date < '2012-04-20' and end_date is null) or
(end_date > '2012-04-20' and start_date < '2012-04-20')
class TSimple (models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField(blank=True, null=True)
...
class TSimpleResource(ModelResource):
def dehydrate(self, bundle):
request_method = bundle.request.META['REQUEST_METHOD']
if request_method=='GET':
new_date = bundle.request.GET.get('new_date', '')
qs = TSimple.objects.raw(
'SELECT * FROM TSimple where (start_date<=\'' +
new_date + '\' and end_date>=\'' +
new_date + '\') or (start_date<=\'' + new_date +
'\' and end_date is null)')
ret_list = [row for row in qs]
// NOT WORK. Not able to get correct json data in javascript.
// It needs return bundle. HOW to replace bundle?
// Is this correct way to do it?
return ret_list
else:
// This is ok.
return bundle
I have following questions:
1) (raw sql method) If implementing in dehydrate method is correct way to do it? If it is, above does not work. It should return bundle object. How to construct new bundle?
If above method is ok, I noticed that bundle already constructed .data field with default query(?), which will be thrown away with new query. That raise the questions if this is right way to do it.
2) If there are other raw sql method to do it? Where to execute the sql?
3) How to do it in filter?
4) I know sql and not familiar with complex filter. That's why I am trying to use raw sql method to do quick prototype. What are the draw back? I noticed that using Tastypie has many unnecessary queries which I don't know how to get rid of it. Example, query on table with foreign key trigger query to another table's data, which I don't want to get.
I figure out the filter and it seems worked. But I am still interested in raw sql.
def apply_filters(self, request, applicable_filters):
base_filter = super(TSimpleResource, self).apply_filters(request,
applicable_filters)
new_date = request.GET.get('new_date', None)
if new_date:
qset = (
(
Q(start_date__lte=new_date) &
Q(end_date__gte=new_date)
) |
(
Q(start_date__lte=new_date) &
Q(end_date__isnull=True)
)
)
base_filter = base_filter.filter(qset)
return base_filter

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

jpa query for arithmetic operation on columns

I am somewhat new to jpa. I have created a few simple queries. But now i have a problem with a simple query. I have an entity Payment with 3 columns(Id,Amount1,Amount2).
Now i want to find all the rows from Payment where Amount1+Amount2 is greater than somevalue.I tried something like:
Query query = getEntityManager().createQuery(
"Select p from Payment p WHERE p.Amount1 + p.Amount2 >' " + someamount +" ' ");
But it is not working. I tried using SUM also but that is only one column.
Can anyone help me with this.
Thanks.
Assuming your entity is properly defined, the following query should work just fine:
final BigDecimal threshold = BigDecimal.valueOf(1000);
TypedQuery<Payment> query = getEntityManager().createQuery(
"SELECT p FROM Payment p WHERE p.Amount1 + p.Amount2> :value",
Payment.class);
query.setParameter("value", threshold);
List<Payment> results = query.getResultList();