Hibernate Criteria SubSelect in select clause - java

Hello guy's having a bit of a problem writing a subselect query with criteria API
sublselect should take a parameter from selected q
SELECT c.file_id as fid, s.person as person, s.fax_no as fax, s.phone_no as phone,(SELECT SUM( b.ammount )
FROM billing b
WHERE b.constants_file_id = c.file_id
) - (
SELECT
CASE
WHEN b.partioa_pay IS NULL
THEN "0"
ELSE SUM( b.partioa_pay )
END
FROM billing b
WHERE b.constants_file_id = c.file_id ) AS totalout
FROM constants c
LEFT JOIN firm_management s ON c.firm_management_firm_managment_id = s.firm_managment_id
WHERE s.firm_managment_id = ?
As you can see the totalout suselected against c.file_id
I was playing with this for 2 days with no luck maby sombody in stackoverflow community who has a strong java and hibernate knowledge would be able to help me..
This is what I got getting exeption 2012-01-17 01:48:06,808 ERROR [org.hibernate.util.JDBCExceptionReporter] - (session F2C61D08758E0AA09CA6C99A5B6F2145, thread 113 invoke ByDefenceFirm.getByDefenceFirm)
Criteria crit = session.createCriteria(Constants.class, "co");
crit.createAlias("co.provider", "pr", Criteria.INNER_JOIN)
.createAlias("co.firmManagement", "ins", Criteria.LEFT_JOIN)
.createAlias("co.law", "lw", Criteria.LEFT_JOIN)
.createAlias("co.billing", "bl", Criteria.LEFT_JOIN)
.setProjection(Projections.projectionList()
.add(Projections.property("co.fileId"))
.add(Projections.property("co.status"))
.add(Projections.property("co.asi"))
.add(Projections.property("pr.name"))
.add(Projections.property("ins.companyName"))
.add(Projections.property("lw.shortName")));
DetachedCriteria valueCrit = DetachedCriteria.forClass(Billing.class, "bl")
.setProjection(Projections.sum("bl.ammount"))
.setProjection(Projections.property("bl.constants"))
.add(Restrictions.eqProperty("bl.constants", "co.fileId"));
crit.add(Property.forName("co.fileId").eq(valueCrit));
crit.setProjection(Projections.property("co.billing"));
crit.add(Restrictions.eq("lw.lawOfficeId", prid));
resultList = crit.list();
If anybody have any suggestions would really appreciated it.

A subselect in the select clause is impossible with Criteria. You'll have to go with a HQL or a SQL query.

It is possible. At least now with the current version of Hibernate. Use "Restrictions.sqlRestriction()".
For example:
Criteria accountCriteria = getCurrentSession().createCriteria(Account.class);
accountCriteria.add(Restrictions.sqlRestriction("{alias}.field IN (SELECT ......)"));
#SuppressWarnings("unchecked")
List<Account> accounts = accountCriteria.list();
Sorry, I didn't read the question carefully. Your scenario is different.

Related

SQL Syntax error in Hibernate's map function

SELECT NEW Map (PRODUCT_CATEGORY, COUNT(PRODUCT_CATEGORY) AS COUNTER) from Product WHERE USER_ID = (SELECT USER_ID FROM USERS WHERE USERNAME='burak123'
Hi everyone,
As hibernates document says here: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select
I am trying to map the query result into a hash map like this
#Query(value = "SELECT NEW Map( PRODUCT_CATEGORY , COUNT(PRODUCT_CATEGORY) AS COUNTER ) from Product WHERE USER_ID=(SELECT USER_ID FROM USERS WHERE USERNAME=(:username)) ",nativeQuery = true)
HashMap<Integer,Integer> getCategoryCountsWithUsername(#Param("username")String username);
But it throws an JdbcSyntaxErrorException. I am trying to solve this for like 1 hours already. Can someone help?
You are using a native query, not an HQL query. Check your SQL syntax.
With a native query, your named parameter won't work. You need to remove the nativeQuery = true

Convert SQL Query to Criteria Query in Spring Boot

I'm relatively new to Spring JPA CriteriaQuery. Im trying to convert my old native query in my program to criteria query and haven't been successful on join query for multiple table with conditions. I need help converting native SQL query into Criteria Query for these query below :
select * from student s inner join (
select distinct on (student_id) * from class where status = 'Active' order by
student_id,date_register desc) c on s.id = c.user_id
inner join teacher t on t.subject_id = c.subject_id
where t.status = 'Active' and s.status='Active' order by s.name desc
Update :
Below code is as far as I can go cause I dont really know much. Am i in the right direction? I'm opting for Expression because i dont know how to use Join.
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> sRoot= query.from(Student.class);
query.select(sRoot);
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Class> cRoot= subquery.from(CLass.class);
Expression<Integer> max = cb.max(cRoot.get("dateRegister"));
subquery.select(max);
subquery.groupBy(cRoot.get("student"));
query.where(
cb.and(
cb.in(cRoot.get("dateRegister")).value(subquery)
)
);
Thanks in advance!

Inner join query on Hibernate - SQL queries do not currently support iteration

I'm new to hibernate and I've this SQL query which works perfectly
SELECT count(*) as posti_disponibili from occupazione t inner join
(select id_posto_park, max(date_time) as MaxDate from occupazione
group by id_posto_park) tm on t.id_posto_park = tm.id_posto_park and
t.date_time = tm.Maxdate and t.isOccupied = 0
which gives me all the last items with isOccupied = 0
I was porting it into Hibernate, I've tried to use
result = ( (Integer) session.createSQLQuery(query).iterate().next() ).intValue()
to return posti_disponibili but i got this exception
java.lang.UnsupportedOperationException: SQL queries do not currently support iteration
How can i solve this? I cannot find the equivalent HQL query
Thank you
I would suggest you to use
Query#uniqueResult()
which will give you single result.
select count(*) .....
will always return you a single result.
Hibernate support it's own iterator-like scroll:
String sqlQuery = "select a, b, c from someTable";
ScrollableResults scroll = getSession().createSQLQuery(sqlQuery).scroll(ScrollMode.FORWARD_ONLY);
while (scroll.next()) {
Object[] row = scroll.get();
//process row columns
}
scroll.close();

Trouble converting SQL Query into JPQL (Eclipselink)

Hey guys, I have the following query and for the life of me I can't seem to translate it into JPQL. The working SQL is:
select * from TB_PRINT_DETAIL y inner join
(select JOB_ID,max(COPY_NUM) MAX_COPY_NUM from TB_PRINT_DETAIL group by JOB_ID ) x
on y.JOB_ID = x.JOB_ID and y.COPY_NUM = x.MAX_COPY_NUM
My feeble attempt at translating it is as follows:
select o from PrintDetailEntity o inner join (select o2.jobId, max(o2.copyNumber) as
maxCopyNum from PrintDetailEntity o2 group by o2.jobId ) as x on o.jobId = o2.jobId and
o.copyNum = o2.maxCopyNum where o.printSuppressionReasonEntity is null
Thanks in advance for any light you can shine!
If I understand your query right (select entities that have the biggest copyNumber among the entites with the same jobId), the following should work:
SELECT o
FROM PrintDetailEntity o
WHERE o.copyNumber =
(SELECT MAX(e.copyNumber) FROM PrintDetailEntity e WHERE o.jobId = e.jobId)

Hibernate Criteria Subquery

I need to do this SQL query with detachedCriteria:
SELECT g.id FROM games g
WHERE NOT EXISTS (
SELECT 1 FROM users_games ug WHERE ug.user_id = 1 AND g.id = ug.game_id)
The idea is to get the ids from the games that aren't owned by the user.
I tried like 10 different approaches with detachedCriteria but I get the "Unknown entity: null" MappingException
The code should look like:
DetachedCriteria subquery = DetachedCriteria.forClass(UserGame.class, "ug")
.add(Restrictions.eq("ug.user.id", 1))
.add(Restrictions.eqProperty("ug.game.id","u.id"));
DetachedCriteria criteria = DetachedCriteria.forClass(Game.class, "g")
.add(Subqueries.notExists(subquery));
Setting also the projections to return only the id of the games.
Any ideas?
I think Hibernate has some trouble joining the queries with no alias.
Adding alias works but the results are quite wrong.
You need to add an alias, as follows:
DetachedCriteria subquery = DetachedCriteria.forClass(UserGame.class, "ug")
.addAlias("ug.user", "user")
.add(Restrictions.eq("user.id", 1))
.addAlias("ug.game", "game")
.add(Restrictions.eqProperty("game.id","u.id"));
That should help
You need a projection and specifies which attribute that needs to be matched.
DetachedCriteria subquery = DetachedCriteria.forClass(UserGame.class, "ug")
.add(Restrictions.eq("ug.user.id", 1))
.add(Restrictions.eqProperty("ug.game.id","u.id"))
.setProjection(Projections.property("ug.game.id"));
DetachedCriteria criteria = DetachedCriteria.forClass(Game.class, "g")
.add(Property.forName("g.id").notIn(subquery));
I hope that helps.
Try
SELECT g.id FROM users_games ug join ug.game g
WHERE NOT EXISTS (SELECT 1 FROM WHERE ug.user_id = 1)

Categories

Resources