I try to make a namedQuery:
#NamedQuery(name = "Interval.findByMemoryType",
query = "select i from Interval i JOIN i.intervalDatas id "
+ "where id.fragments.memoryType = :memoryType")
My problem is, that fragments is a list of fragment. I'm only interested in memory type of first element in the list.
So I should have something like this:
#NamedQuery(name = "Interval.findByMemoryType",
query = "select i from Interval i JOIN i.intervalDatas id "
+ "(select first(id.fragments)) as fid) where fid.memoryType = :memoryType")
But I get always “The query contains a malformed ending” problem.
Could somebody help me??
You can take the first result:
TypedQuery<Interval> q = em.createQuery ("Interval.findByMemoryType", Interval.class);
q.setParameter("memoryType", memoryType);//+other parameters if you have
Interval interval = q.getSingleResult();
The small disadvantage is that it may load all its intervalDatas (depending on the mapping). Also check the documentation for possible exceptions.
Related
I use the following query:
SELECT * FROM phaseinproject as pip JOIN projectinrelease pir
ON pip.projectInRelease_id = pir.id
JOIN releaseperiod as rp ON pir.release_id = rp.id
JOIN releasestructure as rs ON rs.id = rp.releaseStructure_id
JOIN phaseinreleasestructure as pirs ON pirs.releaseStructure_id = rs.id
JOIN releasephase as rlp ON rlp.id = pirs.phase_id
AND rlp.id = pip.phase_id
This query works totally fine. I get three results (the amount I expect).
I convert this query to the following HQL query:
TypedQuery<PhaseInProjectOverview> findPhasesInRelease = em.createQuery("SELECT NEW nl.dashboard.dto.out.PhaseInProjectOverview(phaseInProject.id, phase.name, phaseInProject.startDate, phaseInProject.plannedEndDate, phaseInProject.endDate) FROM PhaseInProject phaseInProject "
+ "JOIN phaseInProject.projectInRelease projectInRelease "
+ "JOIN projectInRelease.release release "
+ "JOIN release.releaseStructure releaseStructure "
+ "JOIN releaseStructure.phaseInReleaseStructures phaseInReleaseStructure "
+ "JOIN phaseInReleaseStructure.phase phase "
+ "WHERE release.id = :releaseId ORDER BY phaseInReleaseStructure.position, phaseInProject.startDate", PhaseInProjectOverview.class);
findPhasesInRelease.setParameter("releaseId", releaseId);
return findPhasesInRelease.getResultList();
No matter what I try: I get 6 results, because HQL does not seem to support the "JOIN ... ON ... AND ..." sql syntax.
Does anyone know how to solve this problem?
edit:
I added my own answer with the used solution. Thank you all for the answers/pointers.
Try the with keyword: phaseInReleaseStructure.phase phase WITH phase.id = phaseInProject.phase_id - this should result in SQL like releasephase as rlp ON rlp.id = pirs.phase_id AND rlp.id = pip.phase_id
Alternatively just add that condition in the where clause:
... WHERE release.id = :releaseId AND phase.id = phaseInProject.phase_id ...
I solved my problem with an extra WHERE clause:
phase.id = phaseInProject.phase.id
Now I get the results I was expecting.
The 'WITH' keyword does not seem to work with multiple entities. When I try, I get an exception:
HQL error: with-clause referenced two different from-clause elements
When trying to use the 'ON' syntax like JOIN phaseInReleaseStructure.phase phase ON phase.id = phaseInProject.id, I get another error:
unexpected token: ON near line 1, column 473
I'm very, very new to Hibernate and JPA. I want to be able to apply ORDER BY and LIMIT clauses to a Hibernate(?) query, but am coming up empty. NOTE: I inherited this code.
Here is the current code:
public SomeCoolResponse getSomeCoolResponse(String myId) {
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id";
Query q = getEntityManager().createQuery(queryString);
q.setParameter("id", myId);
List<MyThings> list = q.getResultList();
if(list.size() > 0) {
return list.get(0);
}
return null;
}
Instead of getting an entire list and then just returning the first result (which is the only one we need), I'd like to be able to apply a LIMIT 0,1 clause so that the query will be faster. Also, the query needs to be sorted descending on aThing.created which is a UNIX timestamp integer.
I've tried altering queryString like this:
String queryString = "select aThing from AWholeBunchOfThings aThing " +
"join aThing.thisOtherThing oThing join oThing.StillAnotherThing saThing " +
"where saThing.subthing.id = :id ORDER BY aThing.created LIMIT 0,1";
But Hibernate still returns the entire set.
I've looked at using the JPA CriteriaBuilder API, but it hurt my brain.
I'm a total n00b when it comes to this, and any help is greatly appreciated!
I think you need
q.setMaxResults(1);
See also the accepted answer here.
How do you do a limit query in HQL?
As to the "order by" clause you may include it in the queryString.
The JPQL equivalent to LIMIT start,max is:
setFirstResult and setMaxResults:
q.setFirstResult(start);
q.setMaxResults(limit);
I need a little help setting up my query. I don't want to have to make multiple selects to form basically the same sub-query if I can avoid it. In a nut shell, I have Objects called TimeSlot that are used to track several details. Those TimeSlot's are items that are paid on. When its time for the TimeSlot to submit for a reimbursement they are used to create a PayableTimeSlot. Before the TimeSlot can be paid I need to make sure it has not been paid already.
As it sits the following is my query:
#NamedQuery(
name = "TimeSlot.by.person.academy.id.by.contract.date",
query = "select distinct ts
from TimeSlot ts
join ts.invitedInstructors ii
join ts.academyClass ac
join ac.academy a
where ii.person.id = ?
and a.id = ?
and ts.schedule.startDateTime BETWEEN ? AND ?
and ts.id not in (select e.id from PayableTimeslot pts join pts.event e)
and ? not in (select e.claimant from PayableTimeslot pts join pts.event e)")
As you can see I am already selecting an element from the PayableTimeSot for the first not in. Is there a way to expand the sub-query into:
(select e.id, e.claimant from PayableTimeslot pts join pts.event e) I am just not sure how to check for multiple items not in the sub-query. By all means if there is a better attack of the problem than the way I am doing it let me know.
Unless you all think the multiple selects wont be a big deal... There will be on average 30-50 entry's a week into the table with each entry being copied (for an audit trail) upwards of 7-9 times.
Okay so after some thinking this is what I came up with. I was indeed trying to answer the problem in the wrong way... I was doing two sub querys when all I needed was a where on the first thus combining the two.
#NamedQuery(
name = "TimeSlot.by.person.academy.id.by.contract.date",
query = "select distinct ts "
+ "from TimeSlot ts "
+ "join ts.invitedInstructors ii "
+ "join ts.academyClass ac "
+ "join ac.academy a "
+ "where ii.person.id = ? "
+ "and a.id = ? "
+ "and ts.schedule.startDateTime BETWEEN ? AND ? "
+ "and ts.id not in (select e.id from PayableTimeslot pts join pts.event e where pts.claimant = ?)")
I am trying to get just the count of the rows returned rather than all the results from the table.
I saw that this can be done like this:
( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()
But when trying to store this query in an integer format(it says cannot convert from Query to Integer)
I am using a dynamic query where the values will be mentioned below the query like this
theQuery = "select count(*) from THM as thm " +
"join thm.TMC as tmc " +
"join tmc.TIMCC as timcc " +
"where thm.Qid = :Qid and thm.Cv = :Cv and timcc.Did = :Did and timcc.Cv= :Cv";
Query query = session.createQuery(theQuery);
query.setInteger("Qid", Integer.parseInt(Qid));
query.setInteger("Did", Did);
query.setInteger("Cv",cV);
Now, how can i get a count of all the rows returned by using Hibernate query in a variable without using list.size but directly from the query?
Have you tried the query.uniqueResult(); ? As your Select count(*) will give you only one number, you should be able to retrieve it with this like int count = (Integer)query.uniqueResult();
To count based on a Criteria you can do this:
Criteria criteria = currentSession().createCriteria(type);
criteria.setProjection(Projections.rowCount());
criteria.uniqueResult();
I'm using the Criteria right now so I know for sure that it works. I saw the uniqueResult() solution on a website here: http://www.jroller.com/RickHigh/entry/hibernate_pagination_jsf_datagrid_prototype1
you can do this
long count = (long)session.createQuery("SELECT COUNT(e) FROM Employees e").getSingleResult();
Try it.
Long count = ((Long) session.createQuery("select count(*) from Book").uniqueResult());
Integer totalBooks = count.intValue();
Work for me
int list=(int)
sessionFactory.getCurrentSession().createSQLQuery("select count(*) as count from
Book").addScalar("count",IntegerType.INSTANCE).uniqueResult();
I have a namedQuery like this:
#NamedQueries ({ ...
#NamedQuery(name = "myUpdate", query = "update User set country = 'EN' where user.id = :id")
...
})
In dao layer
getHibernateTemplate().bulkUpdate(...?)
UPDATE
Query query = sessionFactory.getCurrentSession.getNamedQuery("myUpdate");
getHibernateTemplate.bulkUpdate(query.getQueryString(), id);
I get an error:
Hibernate: update User, set country=EN where id = 2343 ORA-00971: missing SET keyword
Anybody now how can resolve this problem?
UPDATE 2
#NamedQuery(name = "myUpdate", query =
"update User set country = 'EN' where
user.profile.id = ?")
OK
#NamedQuery(name = "myUpdate", query =
"update User set country = 'EN' where
user.profile.name = ?")
NOT OK :(
Unfortunately, that feature is missing in spring, as the named queries are supposed to be used only to retrieve data. One thing you can do is (this is a bit of a work around)
Session session = getHibernateTemplate().getSession();
Query query = session.getNamedQuery("myUpdate");
String update = query.getQueryString();
getHibernateTemplate().bulkUpdate(update, [params]);
I would put that in some kind of helper, so your DAO logic doesn't have to go around spring too.
edit
there's a dangling comma between User and set "update User , set country=EN where"
Actually this is a very old question but I had the same problem today. I realized that the update does not work since you cannont have a join inside of a simple UPDATE. That is also the reason why the comma is added. Hibernate tries to rewrite the query like this:
UPDATE User u, Profile p SET u.country = 'EN' where p.name = ? AND p.id = u.profile.id
To solve the issue you need to select the ids from the second table yourself.
#NamedQuery(name = "myUpdate", query = ""
+ " UPDATE User u "
+ " SET country = 'EN' "
+ " WHERE u.profile.id IN ( "
+ " SELECT p.id "
+ " FROM Profile p "
+ " WHERE p.name = ? "
+ " )"