Hello,
I'm using Hibernate 3.1.3 with MySQL 5.0 and Oracle 9 and I have a problem with a query by example which includes an historized field.
I tkink my context is a very classical scenario. But, I've done two days of googling and searching here, and I'm not finding something that helps me.
I have sone users with positions historiezd by timestamps :
Code:
table-> User id {pk}, name, ...
table-> position id {pk}, user_id {fk}, date, status, office, ...
In the model the object User has a list of Position but only the earliest one is currently valid.
The end-user has a from screen to seach a user (so a query by sample is very usefull).
I'am scratching my head over this query and how to create a Criteria query to complete the query by sample...
I've, first, write this :
Code:
Example ex = Example.create(user);
Criteria crit = session.createCriteria(User.class).add(ex);
crit.createCriteria("positions", "pos")
.add(Expression.eq("pos.status", userStatus);
It's ok, but (as I can predict it) it returns the same user each time a macthing row is found in the history of positions (unless isn't the ealier one).
So this is the SQL I want to translate :
Code:
SELECT u.*
FROM user u, position pos,
(SELECT user_id, MAX(date) AS last_date
FROM position GROUP BY user_id) last_pos
WHERE pos.user_id = last_pos.user_id
AND pos.date = last_pos.last_date;
AND u.id = pos.user_id
AND pos.status = ?
AND a.name = ?
... //others user form fields here
So, I decided to define a subquery to obtain le last position.
Code:
DetachedCriteria subquery = DetachedCriteria.forClass(Position.class, "last_pos");
subquery.setProjection(
Projections.projectionList()
.add( Projections.max("last_pos.date"))
.add( Projections.groupProperty("last_pos.userAgent")
);
Example ex = Example.create(user);
Criteria crit = session.createCriteria(User.class).add(ex);
crit.createCriteria("positions", "pos")
.add(Property.forName("pos.date").eq(subquery))
.add(Expression.eq("pos.status", userStatus);
and I obtain the following exception :
Quote:
java.lang.ClassCastException: org.hibernate.impl.CriteriaImpl$Subcriteria
at org.hibernate.criterion.SubqueryExpression.toSqlString(SubqueryExpression.java:43)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:333)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:82)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:67)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1514)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
...
What I have done wrong ? (I've tried namy variations of that with the same result)
Currently, the cat takes my tongue.
Any kind of help, suggestions, or any link to complex Criteria query samples are welcome.
Thanks,
--
Frantz D.