What is the difference between annotation in method and annotation in attribute

7

Now, I've started to learn and use hibernate recently, and when looking for answers to my questions regarding annotations I've come across the following occasions:

1st) The attribute has the annotation

@Column
private String descricao;

public String getDescricao(){
   return descricao;
}

2nd) The annotation is placed in the get/set of the attribute

private String descricao;

@Column
public String getDescricao(){
   return descricao;
}

I'm using the first option without a specific reason. But it hit the question: what is the difference between them and which is better ( recommendable)?

    
asked by anonymous 23.07.2015 / 15:58

1 answer

3

Although there are discussions recommendation is to use the annotation directly in the attribute , just like you are doing. Home The intention of the ORM , in the case hibernate is to persist the state of the object, so the attributes represent the state of the object.
The intention of mapping an advisory method is questioned by the fact that rarely there is legitimacy in modifying an object's state directly by getting it. For example:

@Column
public String getUnidadeFederativa(){
   uf = (uf == null ? "UF não informada" : uf)
   return uf;
}

The above block may even make sense for a specific local use, but it exceeds the encapsulation boundaries of a originating record of a SGBD , in which consistency is mandatory for this context, the example above would not have constraint in the database with the UF table, ie the encapsulation of the information was affected arbitrarily by an advisory method .

  

So why is it possible to map an advisory method?

There are some specific situations that may be legitimate, but relative, if you need to map information into subclasses of Entity Classes ( third-party ) which does not implement no kind of persistence , the attributes of this entity would be private and you would have to overwrite the advisors and then map them with notes (example taken from Elnur Abdurrakhimov Stack Overflow US )

    
24.07.2015 / 05:11