samedi 21 novembre 2015

Desgin a Java POJO with lazy loading property

Please consider below example:

A web application creates a user object for every logged in user. This object has simple String properties for firstName, lastName ...

Each user can have a car too. Consider that fetching the user car is very expensive, so we prefer not to set the users car when user logs in. Instead we want to get car when a use case needs it.

To implement this we have created a User pojo as:

public class User() {
  private String FirstName;
  private String LastName;   
  private Car cars;
  //Here we have the service object, this could be injected with spring or JEE
  private CarServices carServices;

  public Car getCar() {
    //If the cars is not fetched yet, go on and get it from your service
    if (car == null) {
      car = carServices.getCarFromDB(...)
    }
    return car;
  }

}

To initial user after a login:

User newUser = new User();
newUser.setFirstName("foo");
newUser.setLastName("bar");
//We just let user have service, so he can use this service latter
newUser.setCarServices( new CarServices() );

And every use case which needs the user car can get it easily:

newUser.getCar()

However, I have been argued that in this way my User object is not a simple pojo any more and this is not a good approach.

How can I achieve this requirement in better way.

Aucun commentaire:

Enregistrer un commentaire