9

I have two classes, user and car. Both have ManyToMany mapping to each other.

User:

@Entity
public class User extends Model {

    private int year;

    @ManyToMany(cascade=CascadeType.ALL)
    private List<Car> cars;
}

Car:

@Entity
public class Car extends Model {
    @ManyToMany(mappedBy = "cars", cascade=CascadeType.ALL )
    private List<User> users;
}

Using ebean, I would like to query only those cars from year 1999 that have give user in their list. I do not want to iterate over the user's car list in Java code.

I didn't find any documentation how many-to-many queries should look like. So I would something like this:

public List<Car> findCars(int year, User user) {
    return Car.find.where().eq("year", int).eq("users", user).findList();
}

Is this possible with Ebean?

Franco
  • 11,845
  • 7
  • 27
  • 33
Petteri H
  • 11,779
  • 12
  • 64
  • 94

1 Answers1

14

Check similar question (and answer)

Most probably your finder should look like:

public List<Car> findCars(int year, User user) {
    return find.where().eq("year", year).eq("users.id", user.id).findList();
}

BTW I assume that you have some id field but just didn't show us. Also make your fields public, so you won't need to write getters/setters for each.

Community
  • 1
  • 1
biesior
  • 55,576
  • 10
  • 125
  • 182
  • I was using private fields as I had issues getting tests working without getters/setters. http://stackoverflow.com/questions/13011874/why-ebean-returns-null-for-no-reason – Petteri H Nov 16 '12 at 16:46
  • Yes with private fields, you need to write public getters, that's normal – biesior Nov 16 '12 at 16:56
  • Obviously :-) But the link in my comment describes bug/feature in Ebean / Play 2 combo I was referring to. – Petteri H Nov 16 '12 at 17:30