Search code examples
postgresqlactivejdbcjavalite

ActiveJDBC select record from multiple tables with an aggregate


Here is the situation. I have one table with multiple many-to-many relationships.

game (id, name, year_release ...)
game_price (game_id, price_id, amount)
price(id, label -- new game, used game)
category(id, name)
game_category(game_id, category_id)

Now I want to select a list on 20 games with for each game, the list of prices and the list of categories.

In SQL I would do something like this

select game.id, game.name string_agg(price.label||':'game_price.amount), string_agg(category.name)
from game
left join game_price gp on (game.id = gp.game_id)
left join price on (price.id = price_id)
left join game_category gc on (game.id = gc.game_id)
left join category on (category.id = category_id)
group by game.id

I have an example here: http://javalite.io/lazy_and_eager for a 1-to-many but nothing for many-to-many.

Do I have to first load all game_price then all game_category, like this ?

List<GamesPrices> gamesPrices = GamesPrices.findAll(Game.class, Price.class)
List<GamesCategories> gamesCategories = GamesCategories.findAll(Game.class, Category.class)

But then how can I loop to get all information for each game?


Solution

  • There are two ways to do it:

    With Models:

    List<Game> games = Game.where(criteria, param1, param2).include(Price.class, Category,class).limit(20);
    for(Game g: games){
       List<Price> prices = g.getAll(Price.class);
       List<Category> categories = g.getAll(Category.class);
    }
    

    Without models:

    String sql = "select game.id, game.name string_agg(price.label||':'game_price.amount), string_agg(category.name)" + 
    "from game" + 
    "left join game_price gp on (game.id = gp.game_id)" + 
    "left join price on (price.id = price_id)" + 
    "left join game_category gc on (game.id = gc.game_id)" + 
    "left join category on (category.id = category_id)" + 
    "group by game.id";
    
    List<Map> results = Base.findAll(sql);
    

    I hope it helps!