1

I've two POJOs in Java: Movie to use in my database and other Movie to use like result from request to webservice.

package .service
public class Movie{
 @Serialized("Title")
 private String title;
 @Serialized("Year")
 private String year;
 @Serialized("Poster")
 private String poster
}

package .database
public class Movie{
  @ColumnInfo(name = "title")
  private String title;
  @ColumnInfo(name = "year")
  private String year;
  @ColumnInfo(name = "poster")
  private String poster;
}

I've solved this by creating a class that does the conversion:

 public class MovieObjectAdapter {
    public static List<service.Movie> castFrom(List<database.Movie>moviesDatabase){
        List<service.Movie> moviesModel = new ArrayList<>();
        for (database.Movie movie:
             moviesDatabase) {
            service.Movie movieModel = new service.Movie();
            movieModel.setTitle(movie.getTitle());
            movieModel.setPoster(movie.getPoster());
            movieModel.setYear(movie.getYear());
            moviesModel.add(movieModel);
        }
        return moviesModel;
    }
}

But I'm not very happy with this. So which design pattern can you recommend for me to use?

Edit:

Oh I´m sorry i forgot a little detail, my service have another attributes names that my database, that is the reason of i´ve have two pojos. Sorry for omit this.

Daniel Carreto
  • 211
  • 1
  • 9

3 Answers3

1

I have done this with Mapper class

public final class Mapper {

   public static service.Movie from(database.Movie dMovie) {
      service.Movie movie = new service.Movie();
      // set the properties based on database.Movie
      return movie;
   }
}
Harpz
  • 183
  • 1
  • 12
1

You can use a technique called "reflection". Like in this article: https://www.javainuse.com/java/chap1 This technique is potent for tasks like mapping one object to another. But it has one drawback - such mapping may be slow (relatively, compared with direct mapping, as you do). But, I think, in your case, it's an ideal solution.

Alex Shevelev
  • 681
  • 7
  • 14
0

Movie from service package and Movie from database package have same attributes. You should consider having a package for common objects. For example using Movie from application main package wherever needed either in service or in database is much easier and clear.

Gratien Asimbahwe
  • 1,606
  • 4
  • 19
  • 30