ebean-orm / ebean

Ebean ORM
https://ebean.io
Apache License 2.0
1.46k stars 260 forks source link

Sorting on a ManyToMany relationship #3419

Open Ichtil opened 3 months ago

Ichtil commented 3 months ago

Expected behavior

Querying a bean with a Many to Many relationship and sorting on that relationship should not duplicate returned list. I am not sure if sorting by many to many relationship is a supported scenario.

Actual behavior

Query returns duplicate beans.

Steps to reproduce

Please see attached failing PR https://github.com/ebean-orm/ebean/pull/3418

rbygrave commented 3 months ago

if sorting by many to many relationship is a supported scenario

This case is where the query is sorting by many to many AND not fetching that many to many. So when we look at the SQL we see:

select distinct t0.userid, t0.user_name, t0.user_type_id, t1.roleid 
from muser t0 
left join mrole_muser t1z_ on t1z_.muser_userid = t0.userid 
left join mrole t1 on t1.roleid = t1z_.mrole_roleid 
order by t1.roleid;

... but as the M2M "roles" are not fetched the order by (and joins that are required to support the order by) is very academic.

That is, for the query:

DB.find(MUser.class)
      .orderBy("roles")
      .findList();

... the orderBy does not actually have utility value. The orderBy is useful when the query also includes a .fetch("roles").

Options:

So the options for a query with an orderBy() on a M2M relationship but with no associated fetch of the M2M.

Hmm.