Search code examples
playframeworkplayframework-2.0ebean

Inner joins in Ebean?


I read https://archive-avaje-org.github.io/ebean/introquery_joinquery.html looking at Example A, I noticed there's no specification of the inner join common column. I think their fetch-tablename syntax causes Ebean to look at what column the 2 tables have to inner join on. Then they are storing each result as an Order? They are joining 2 tables, so how can they store columns from the customer table as an Order?

I tried to do an inner join with ebean in my code and discovered at least one of my assumptions was wrong. I have 2 tables, a Street table and a House table(one to many relationship). The street_id column in the House table is the foreign key to the id column of the Street table. I'm trying to come up with the Ebean equivalent of this sql:

SELECT s.name, h.owner, h.isSubscriber FROM Street as s INNER JOIN House as h WHERE     
h.street_id=s.id AND h.isNew='false'

Solution

  • I believe that you just reference the table directly in the where ExpressionList to require an inner join, something like:

    Ebean.find(House.class)
         .select("street.name, owner, isSubscriber")
         .where()
         .eq("street.id", s.id)
         .eq("isNew", false)
         .findList();
    

    This assumes that you have a House Entity setup similar to this:

    @Entity 
    public class House extends Model {
    
        @Id 
        public Long id;
    
        @ManyToOne
        public Street street;
    
        ...
    }
    

    And a Street Entity like this:

    @Entity 
    public class Street extends Model {
    
        @Id 
        public Long id;
    
        @OneToMany(mappedBy = "street")
        public List<House> houses;
    
        ...
    }