问题
I have a method in my Model class which queries DB with the help of Finder:
public static List<Bet> getBetsByUser(User user){
System.out.println("ROW COUNT: "+ find.fetch("user")
.fetch("moneyPoolEntity.account")
.fetch("coupon.moneyPoolEntities.account")
.fetch("moneyPoolEntity.bettingTable")
.fetch("moneyPoolEntity.moneyPoolType.currency").setDistinct(true)
.where().eq("user", user).findRowCount() );
List<Bet> betList = find.fetch("user")
.fetch("moneyPoolEntity.account")
.fetch("coupon.moneyPoolEntities.account")
.fetch("moneyPoolEntity.bettingTable")
.fetch("moneyPoolEntity.moneyPoolType.currency").setDistinct(true)
.where().eq("user", user).findList();
System.out.println("LIST COUNT: "+betList.size());
for(Bet b : betList){
System.out.println(b.id+" b.coupon.moneyPoolEntities.size() = " + b.coupon.moneyPoolEntities.size());
for (MoneyPoolEntity mpe : b.coupon.moneyPoolEntities){
System.out.println("mpe--"+mpe.id+" ; account: "+mpe.account.id);
}
}
return betList;
}
Useful to say that there is 3 entities in each coupon.moneyPoolEntities list. So, in case size of the output is 1, everything is fine and I have: .findRowCount() = 1 betList.size() = 1 while .coupon.moneyPoolEntities.size() = 3 and manual SQL querying returns table:
with all equal fields except MoneyPoolEntity.id and Account.id. So Ebean is able to pack 3 entities into .coupon.moneyPoolEntities list.PrintLn result looks like:
ROW COUNT: 1
LIST COUNT: 1
243 b.coupon.moneyPoolEntities.size() = 3
mpe--201 ; account: 241
mpe--203 ; account: 243
mpe--202 ; account: 242
bets.size() = 1
The problem arrives when I add one more Bet entity still with 3 entities in coupon.moneyPoolEntities list.
SQL query result looks like:
But now instead of two Bet entities each with coupon.moneyPoolEntities of size 3 Ebean packs it in a very strange way:
PrintLn result:
ROW COUNT: 2
LIST COUNT: 4
261 b.coupon.moneyPoolEntities.size() = 2
mpe--202 ; account: 242
mpe--203 ; account: 243
243 b.coupon.moneyPoolEntities.size() = 2
mpe--202 ; account: 242
mpe--203 ; account: 243
261 b.coupon.moneyPoolEntities.size() = 2
mpe--202 ; account: 242
mpe--203 ; account: 243
243 b.coupon.moneyPoolEntities.size() = 2
mpe--202 ; account: 242
mpe--203 ; account: 243
bets.size() = 4
WHY?
回答1:
I've solved the problem. For some reason PostgresDB was sometimes returning sorted table and sometimes not (although I haven't asked to sort it).
The problem is that Ebean in my case joins correctly only if the table is sorted.
So, the workaround that works for me is the addition of .orderBy("id") to the fetch sequence.
来源:https://stackoverflow.com/questions/20068478/ebean-finder-joins-onetomany-fields-in-a-strange-way-4-results-instead-of-2