I have the next query :
String queryString = "from Visit vis "
+ "LEFT OUTER JOIN FETCH vis.pdv vis_pdv ";
return query.list();
After that, I get the next error when I try to access to some pdv:
nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists
The point is I have some corrupt data, so "Visit" has sometimes an id in "pdv" but it doesn't exist that pdv in the table "PDV". I would like to handle this in the query, so it doesn't return corrupt data. Is there any way?
Thanks
There's a similar issue here: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: Single table query
Basically the answer is: you need to have a consistent database before Hibernate can work with the data.
I understood that you have a Visit.pvd column that is a foreign key into the PVD table but contains data that isn't reflected in PVD. That's your integrity violation. What you can do is bypassing Hibernate and collect any Visit.ids that are identifying entities that are invalid:
session.createSQLQuery("SELECT id FROM Visit "
+ "WHERE pvd NOT IN (SELECT p.id FROM pvd)").list();
This gets you a List<Object[]> that you can iterate to get the offending entities. Use that to UPDATE them to not contain invalid references (or just use a plain UPDATE with the WHERE clause I gave).
In hibernate whene you use join in HQL it returns List so please cast your return satement as return
List<Object[]> query.list();
and retrun type as
List<Object[]>
and for your question
try like this
select vis from Visit vis, Pdv pdv where vis.id=pdv.vis.id
this query will return
List<Visit>
String queryString = "from Visit vis "
+ "LEFT OUTER JOIN FETCH vis.pdv ";
return query.list();
you dont need List<Object[]> as your returning List<Visit>
List<Object[]>
is needed when you are returning multiple object from the query.
eg select v.pid,v.pname,v.pvisit from Visit v
Related
I have a JPQL query in a repository that is the equivalent of the MySQL query below:
SELECT DISTINCT ji.* FROM tracker_job_item AS ji
JOIN tracker_work AS w ON ji.id=w.tracker_job_item_id
JOIN tracker_work_quantity AS wq on w.id=wq.tracker_work_id
WHERE w.work_type = 'CUTTING' AND ji.is_finished=0
GROUP BY wq.tracker_work_id
HAVING ji.quantity != SUM(wq.received_quantity)
The MySQL version works just fine, but the JPQL equivalent gives an exception: Unknown column 'jobitem0_.quantity' in 'having clause'
The JPQL query is like below:
#Query("select distinct ji from JobItem ji" +
" join Work w on ji.id=w.jobItem.id" +
" join WorkQuantity wq on w.id=wq.work.id" +
" where w.workType='CUTTING' and ji.isFinished=false and ji.jobItemName like %:search%" +
" group by ji.id" +
" having ji.quantity != sum(wq.receivedQuantity)")
Page<JobItem> findAllActiveCuttingJobs(Pageable pageable, #Param("search") String search);
Please help me with why I'm getting the error even though the field quantity exists in JobItem.
You can't reference a column in the having clause that isn't in the group by clause, definitely in JPA and (normally at least) in SQL. Looks like MySQL is letting you get away with it but JPA isn't.
See here:
http://learningviacode.blogspot.co.uk/2012/12/group-by-and-having-clauses-in-hql.html
I have a table/entity called Recipe with a child collection of type Tag.
I want to be able to find a Recipe searching by two or more tags. Something like:
SELECT re FROM Recipe re JOIN re.tags t WHERE t in :tagsIds
but I only want those hits where the Tag collection contains all tagIds.
Is it possible in HQL/SQL? (Maybe using Criteria?)
Thanks in advance.
I am assuming you have two different entities Recipe and Tag, it can be done as below.
Criteria criteria = getSession().createCriteria("Recipe.class");
criteria.createAlias("tags", "tag");
criteria.add(Restrictions.in("tag.id", Arrays.asList(1,2,3)));
return (List<Recipe>) criteria.list();
I believe you may be missing parentheses in the HQL. It should be:
... WHERE t in (:tagsIds)
Ok, so this did it. Thanks for the replies.
String hql = "select r from Recipe r " +
"join r.tags t " +
"where t.id in (:tags) " +
"group by r " +
"having count(t)=:tag_count";
Query query = session.createQuery(hql);
query.setParameterList("tags", tagIds);
query.setInteger("tag_count", tagIds.size());
List<Recipe> recipes = query.list();
I'm triggering a query using HQL, normally it should return empty resultset as it doesn't have any records w.r.t it. But, it throws
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
My code is
String hql = "FROM com.pck.Person where userId = " + userId;
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Dashboard> listUserDetails = query.list(); <-- Problem here.
I'm expecting list size is 0 because there are no records w.r.t userId passed.
What changes do I need to do?
Lets say the value of userId was "abc12"
Given your code, the value of the string called hql would become:
"FROM com.pck.Person where userId = abc12"
If you took the value of that string and tried to run it as a query on any database, most of them would fail to understand that abc12 is a string. Normally it would be interpreted as a variable.
As other users mentioned including the single quotes would produce the desired query, but the recommended way to assign parameter values is this:
String hql = "FROM com.pck.Person where userId = :id"
query.setParameter("id", userId);
Looks like you are missing single quotes around userid.
Try with "FROM com.pck.Person where userId = '" + userId + "'";
or
Use named parameters with query.setParameter("userid", userId);
Posting the full stacktrace would help if this doesn't solve.
I am trying to get all the table names in a database(Oracle 11g) to dynamically generate checkboxes for each table in the UI. I have not mapped any of these tables in the .cfg.xml file.
I used the below code :
List<Object> list = sessionProd.createQuery("select table_name from user_tables").list();
for(Object l : list){
System.out.println("L : " +l.toString());
}
But it errored as below :
org.hibernate.hql.internal.ast.QuerySyntaxException: user_tables is not mapped [select table_name from user_tables]
Please let me know if there is any way to get all table names in Hibernate 4
You need to use SQL query, not HQL query
sessionProd.createSQLQuery("select table_name from user_tables").list();
Using a native SQL query method resolved the problem. Thanks for your suggestions.
The following code worked for me:
List<Object> list = sessionProd.createSQLQuery("select table_name from user_tables").list();
I think the query is not proper. Try with the below snippet
List<Object> list = sessionProd.createQuery("show tables from Database_name").list();
change the query string with select table_name from all_tables
List<Object> list = sessionProd.createQuery("select table_name from all_tables").list();
for(Object l : list){
System.out.println("L : " +l.toString());
}
Hibernate would return Exception to you in such case because you have not mapped user_tables. If you want to get all table names you should to create SQLQuery, that would return to you that you need. You can use HQL (createQuery) only for mapped tables
I am new to new to hibernate and Java, so I apologize if these are ridiculously simply questions.
I don't understand why the following query gives me the error "ORA-00979: not a GROUP BY expression".
Query q = session.createQuery (
"select new tdata.Summary(tbForm.rYear, SUM(tbForm.pWaste)) "
+ "from TrForm tbForm "
+ "left join fetch tbForm.indKey "
+ "where tbForm.indKey.grpCode='999' "
+ "group by tbForm.rYear " );
The possible reasons for this error do not seem to apply to my query because I am including group by function SUM, and I do not have any expressions in the select that are not in the group by.
I also tried to write a criteria query to do what I need, and I could not get that to work either. In the criteria version, I am confused as to how to add restrictions to fetched data and how to get the data into the Summary object.
Criteria criteria = session.createCriteria(TrForm.class)
.setFetchMode("DimInd",FetchMode.JOIN)
.add(Restrictions.eq("indKey.indCode", "999"))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("rYear"))
.add(Projections.sum("pWaste")));
summaryList = (List<Summary>) criteria.list();
Any help would be greatly appreciated.
Thanks!
Update:
Thank you so much! I removed the "left join fetch tbForm.indKey" and the HQL version worked!
Generalized query is
select R_YEAR, sum(P_WASTE)
from TR_FORM tbForm
left join DIM_IND ind
on tbForm.IND_KEY = ind.IND_KEY
where ind.GRP_CODE='999'
group by tbForm.R_YEAR
tdata is the folder in which I have the java code for the data models.