How to get multiple instances of same entity from a query

30 views
Skip to first unread message

sasikanth dale

unread,
Sep 23, 2016, 6:45:07 PM9/23/16
to Querydsl
Can any one help me figure out the below issue.

i'm trying to retrieve tuple list from a query.
example: a person can be a manager and a person can be a officer as well (different person) they both can attend safe facility every day.
here is my query.

QPerson manager = QPerson.person;
QPerson officer = QPerson.person;
query.from(qfacility, manager, office).where....

after executing this line i get an error 'person is already used'.
basically i'm expecting one tuple object should contain both person objects. 
Thanks. 

Richard Richter

unread,
Sep 24, 2016, 11:33:19 AM9/24/16
to Querydsl
Hi

Of course the person is already use, because "person" is QPerson.person "alias" and both variables - manager and officer - point to the same instance. This is typical trap for adopters, but it's logical from Java point of view as well. You're using two different local variables, but they mean the same thing - exactly the same instance. What you want is:
QPerson manager = QPerson.person; // the first one can be this
QPerson officer = new QPerson("officer"); // the other MUST be different instance

Personally, whenever query requires more of the same type, I don't use the default alias (QPerson.person), but always opt for new instance, that is even manager:
QPerson manager = new QPerson("manager"); // better name based on person's role

That should do the trick. :-) I'd also use joins instead of multi-from, but that's another issue and not necessarily a problem. But being explicit is always better.

Hope it helps

Cheers

Virgo

sasikanth dale

unread,
Sep 25, 2016, 12:28:06 PM9/25/16
to Querydsl
Thank you for the trick.
Reply all
Reply to author
Forward
0 new messages