I'm working with JPQL, I want to remove all the duplicated rows using DISTINCT, and at the same time retrieve all the columns in a table, I wrote something like this:
SELECT DISTINCT cl.name, cl.age
FROM Client AS cl
WHERE cl.country='****'
This query returns just the two columns name and age.
Assuming you have a unique id you could write your query to use GROUP BY as follows:
SELECT client FROM Client client
WHERE client.id IN (
SELECT MIN(c.id)
FROM Client c
WHERE c.country='****'
GROUP BY c.name, c.age
)
You should not retrieve all the fields of Client because you should not select non-aggregated fields.
Try this :
DELETE from Client c
Where c.name IN (SELECT DISTINCT cl.name
FROM Client AS cl
WHERE cl.country='****')
But pay attention to your persistence context to avoid corrupt data.
Related
I have a record that I need to do some validation on. This record can potentially have multiple children. I need to create a collection (I was planning on using a standard list) containing the ID of every child record but this needs to be recursive (i.e. each child record can also have child records of its own, and I need each of those IDs as well, ad infinitem).I'm using MSSQL Server for my DB but I'm not too sure how I would structure the necessary SQL query.
This is what I have tried;
DECLARE #Id VARCHAR(30) = '[Record Id]';
WITH cte AS
(
SELECT record.id, record.parentid
FROM records r
WHERE id = #Id
UNION ALL
SELECT record.id, wo.parentid
FROM records r JOIN cte c ON wo.parentid = c.id
)
SELECT id
FROM cte;
I get the following error:
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
I have 2 tables TABLE1 and TABLE2.Table1 is having name and Table2 is having email and Phone.
To get the name,email and phone,I query as below
query = entityManagerUtil.createNativeQuery("select s.Name,c.Phone1,c.Email1 from Table1 s,Table2 c where c.id= s.NodeID and s.NodeID =21")
Now my next requirement is to update name,email and phone.As these parameters are present in different tables so I am searching for single query which will update 2 tables.Unfortunately I am using sql server and there is no way to update 2 tables using single query
So I am thinking to use #Transactional and 2 queries to update 2 tables like the follow
#Transactional
public void updateDetails()
{
Query query1= entityManagerUtil.entityManager.createNativeQuery("update Table1 set Name='' where id in (select NodeID from Table 2) and NodeID=21");
Query query2= entityManagerUtil.entityManager.createNativeQuery("update Table2 set Email='' and phone1='' where NodeID in (select id from Table 2) and NodeID=21");
query1.executeUpdate();
query2.executeUpdate();
}
Is there any other better way to update 2 tables?
you can use JDBCTemplate
http://sujitpal.blogspot.com.es/2007/03/spring-jdbctemplate-and-transactions.html
It allows to do multiple queries with one connection, so you save some time instead of doing it twice.
Why don't you use Hibernate entities for that. Just load the entities associated with Table1 and table2, modify them and let the automatic dirty checking mechanism to update the tables on your behalf. That's one reason for using an ORM by the way.
I have two tables:
Client (clientId, firstName, lastName, gender)
Event (clientId, eventId)
I need to represent a query similar to the following using Criteria:
SELECT c.clientId, c.firstName, c.lastName, c.gender, MAX(eventId)
FROM Client c JOIN Event e ON c.clientId = e.clientId
GROUP BY c.clientId, c.firstName, c.lastName, c.gender
I have tried this:
final Criteria criteria = session.createCriteria(Client.class);
criteria.setFetchMode("Event", FetchMode.JOIN);
criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("clientId")).add(Projections.max("eventId")));
but it throws an exception on the last line with the message:
HibernateQueryException: could not resolve property: eventId of:
Client
How can I specify the join between the Client table which itself contains no column related to the Event table but the clientId column on the Event table is a foreign key back into the Client table?
As you can see, it's really driven off the Client table and that I only need to select the maximum eventId from the Event table. Also, as I mentioned, I am trying to make a change to an existing Criteria query which is based on the Client class. It is used to retrieve all the columns for all active clients. I just need to add one extra column to the query results - the maximum eventId.
Use alias
Criteria criteria = session.createCriteria(Event.class, "et").
createAlias("et.Client", "ct").
setProjection(Projections.projectionList().
add(Projections.groupProperty("et.clientId")).
add(Projections.max("et.eventId")));
For more details on criteria, refer Criteria Queries
That is obvious. Because Client class does not have eventId property, and your criteria is defined for Client class.
When trying to use a property of B class inside a Criteria for A, you have to use Aliases.
All you have to do is to modify your code like this:
final Criteria criteria = session.createCriteria(Event.class, "event");
criteria.createAlias("event.client", "client");
criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("clientId")).add(Projections.max("eventId")));
UPDATED (based on your comment)
As your query needs Event class, you have to have a Criteria for this class. So you have to something like this:
final Criteria criteria = session.createCriteria(Event.class, "event");
criteria.createAlias("event.client", "client");
//The criteria below, is returning clientId
DetachedCriteria eventCr = DetachedCriteria.forClass(Event.class, "event");
eventCr.setProjection(Projections.projectionList().add(Projections.groupProperty("clientId")).add(Projections.max("eventId")));
//Now using subqueries you can achieve your goal
criteria.add(Subqueries.propertyIn("clientId", eventCr));
I don't know for sure what you're looking for, but I hope I have given you some good hints. You might want to try Subqueries.propertyEq instead if your query must return a single id.
I am fetching records from my "record" table. "record" table has many columns tow of which are
client_id, foreign key mapping to client table.
creation_date , date of record creation
I would like to do a query on this table , but I would like to fetch only one record per client(latest creation_date record has preference).
Will following work?
select r.id,r.xx,r.yy
group by(r.client_id),r.creation_date
from record r
order by creation_date desc
I tried above and seems records fetched are not of latest creation dates.
Hope my question is clear
Just keep your query and add a WHERE condition :
SELECT r.id,r.xx,r.yy
GROUP BY(r.client_id)
FROM record r
WHERE r.creation_date = (SELECT MAX(creation_date) FROM record tmp WHERE tmp.client_id = r.client_id )
Take a look at This discussion
This should give you a good starting point in HQL.
from Record as r inner join fetch r.client
where r.creation_date > (
select max(rec.creation_date) from Record rec
where rec.client.client_id = r.client.client_id
)
This of course assumes that your Record has a reference to its parent Client called client.
Hi I´m using Eclipselink and I did a native query to select some fields of 2 tables. I mapped my table Logins in a model class. I would not like to map my table "B" because I need only 2 fields of this table on my sql result.. can I map this 2 fields in my Logins table to my sql result ?
My sql is this:
select l.login_id, s.lugarcerto,s.vrum, l.username, l.first_name, l.last_name, l.phone, l.fax_number, l.address, l.zip,
l.address2 as 'birth_date', l.city as 'cpf_cnpj'
from Logins l
join (select se.login_id, lugarcerto = min(case when se.service = 'IM' then '1' end), vrum = min(case when se.service = 'VE' then '1' end)
from (select distinct ad.login_id, substring(ap.Rate_code,(CHARINDEX('-', ap.Rate_code)+1),2) as 'service'
from Ad_Data.dbo.ad ad
join Ad_Data.dbo.ad_pub ap on (ad.ad_id = ap.ad_id)
where ap.ad_type =1) se
group by se.login_id) s on (s.login_id = l.login_id)
I did map Logins table and I want to map s.lugarcerto and s.vrum to my SQL query result.
There´s anyway to just add it to my Logins model ?
Not without having mappings for the attributes you want those values put into, and not without causing problems with them being cached in the entity.
Why not just return the values beside the entity, much like you would with a JPQL query such as: "Select l, subquery1, subquery2 from Logins l" ie:
Query q = em.createNativeQuery(yourQueryString, "resultMappingName");
And in the entity, include the annotation:
#SqlResultSetMapping(name="resultMappingName",
entities={#EntityResult(entityClass=com.acme.Logins.class, )},
columns={#ColumnResult(name="LUGARCERTO"), #ColumnResult(name="VRUM")}
)
Best Regards,
Chris