U
U
UxName2016-07-21 13:35:39
Java
UxName, 2016-07-21 13:35:39

Android. How to combine ORM model and OOP model?

There is an OOP class model that the application works with, for example

class User {
String name;
String password;
}

And there is a REST model for Retrofit that the application accepts when the server responds, for example:
class User {
String responseStatus;
String name;
String password;
}

And there is also a structure for working with the database (Sqlite) through ORMlite:
class User {
@DatabaseField (autoincrement = true) int id;
@DatabaseField String name;
@DatabaseField String password;
}

All these classes are 90% similar to each other, but different libraries need their own, additional fields (for example, the id field for ORM). Tell me the bestpractices for this case, is it necessary to combine all classes into one, with all fields
[
 int id (for ORM) ;
 String responseStatus (for REST) ;
 String name (for OOP) ;
 String password (for OOP) ;
]
?
Or is it better to allocate a separate class for each library, and if one of them changes, make changes manually to all the others?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sirs, 2016-07-21
@uxname

It's not worth putting everything in one class. The classes that you use for REST declare as dto objects, they must change synchronously both on the client and on the server. For communication between what is in the rest and what is in the database - write the simplest converters at the service level.
UPD
Simplest example:
dto class :

class User {
String responseStatus;
String name;
String password;

public User(final String responseStatus, final String name, final String password){
this.responseStatus=responseStatus;
this.name = name;
this.password=password;
}

//setters
//getters
}

entity model for orm:
class UserEntity {
@DatabaseField (autoincrement = true) int id;
@DatabaseField String name;
@DatabaseField String password;
//getters
//setters
}

you have a simple service that transfers data from the controller to the database layer, for example
public class UserService(){

//some field

public void addUser(final User user){
//some code
UserEntity userEntity = convert(user);
//save userEntity into db
}

private UserEntity convert(final User user){
//some if 
//some logger
UserEntity userEntity = new UserEntity();
userEntity.setName(user.getName());
userEntity.setPassword(user.gerPassword());
return userEntity;
}
}

This is the simplest example, there can be many options - various mappers, builders, converters, etc. It depends on the frameworks used and the approach taken on the project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question