vendredi 20 mai 2016

JPA: multi language entity and code duplication

Let's suppose that we need to develop some service for all clients. And some clients will use only single language version (situation 1) and some will use only multiple language version (situation 2). The service is about Book entity.

So in DB, we have three tables (remember, we do service for both situations)

book_sl: id, name
book_ml:id
book_ml_text:id,fk,language,name

The first attempt was to make one Book class fro both situations:

class Book{
 int id;
 String name;
 String language;//????
}

However, this solution didn't work, because it is impossible to add a new translation in case of multi language use. Because when we do em.persist() JPA provider will insert in both tables book_ml and book_ml_text. And besides it is not clear with field language - how to make it to ignore in certain cases.

So another solution is

class BookSl{
  int id;
  String name;
}
class BookMl{
  int id;
  List<BookMlText> texts;
}
class BookMlText{
  int id;
  String language;
  String name;
}

This solution can work, however, this solution doubles all the code of service. The reason is that, that creating two types with different structure we need to create two service implementation, two times more tests etc.

So the question - how to avoid code duplication with multi languge approach with JPA?

Aucun commentaire:

Enregistrer un commentaire