How to reconcile good Object Oriented practices and ORM frameworks for getters and setters?

1

In many of the systems I have worked with or have had contact with, the class that represents a model is usually a POJO, which mapped its attributes for columns (for relational databases) or attributes (for some NoSQL databases). Thus, in many of the the getters and setters to bring and bring the data to the database. But good object-orientation practices tell us that we should not expose the internal structure of our objects by exposing, instead operations that alter the internal state of the objects and maintain the consistency of the object state.

Let's give an example. Let's say we have the Client class. This class has an identifier, the name of the client, and the date of the last change. We can not alter these data, but we want to persist them. If we want to change the name, we will also have to change the id and last change date.

The ORM needs the getters and setters methods, so we have:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}

As it stands, anyone other than the ORM itself could change the object ID, causing undesirable effects on the rest of the system.

On the contrary, if we were to change using the class to respect the rules of object orientation, we would have something like this:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}

My question is:

How to reconcile these best practices with the needs of the ORM frameworks?

    
asked by anonymous 31.03.2017 / 13:54

1 answer

0

If I'm not mistaken in the case of @id it ignores the get / set methods unless you put the @id in the get, but there is the @Access annotation that sets whether you ORM will access via Field or Property.

link

    
31.03.2017 / 14:36