Suppose I have 2 models
Public class Bus extends Model{
@OneToMany(mappedBy="bus")
private List<Passenger> passengers;
public Bus(passengers){
this.passengers=passengers;
}
public List<Passenger> getPassengers(){
return passengers;
}
}
public Class Passenger extends Model{
@ManyToOne
private Bus bus;
public Passenger(Bus bus){
this.bus=bus;
}
}
Can I use a controller method that finds all the passengers in a bus using the getter. eg:
public static void getPassengers(Long busId){
Bus bus = Bus.findById(busId);
List<Passengers> pList = bus.getPassengers();
}
I tried it in a real play web application but the List size returned is always 0.
Thanks in advance.
Yes, you can. But I think the problem isn’t using a getter, it is that you have not constructed your models correctly.
There are 3 problems I see in your example:
In your controller action
getPassengers(Long busId)you need to changeList<Passengers>toList<Passenger>(singular “Passenger”)In your
Busmodel class, you need to either makepassengerspublic or declare a public setter. The “Play!” way is to just declare fields as public and let the framework generate the getters and setters for you. The only reason you would declare your own getters and setters is if you needed to add some logic.In your
Passengermodel class, you need to makebuspublic.Here’s how I would fix your code:
And your controller action:
If this doesn’t fix your problem, then you are not loading your data correctly. You should post the code you are running to actually create the records – whether that be loading a YAML file or whatever.