What is the difference between method annotation and attribute annotation

Asked

Viewed 239 times

7

Guys, I started learning and using the hibernate recently, and while searching for answers to my questions regarding the annotations I have come across following occasions:

1st) The attribute has the annotation

@Column
private String descricao;

public String getDescricao(){
   return descricao;
}

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

private String descricao;

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

I am using the first option without a specific reason. But hit the doubt: what is the difference of them and which is better (recommendable) utilise?

  • Follow the Soen link with your question, http://stackoverflow.com/a/6084701

1 answer

3


Although there are discussions recommendation is to use the annotation directly in the attribute, just like you’re doing.

The intention of ORM, in the case Hibernate, is to persist the state of the object, thus attributes are the representation of state of the object.

The intention to map an advisory method is questioned by the fact that seldom there is legitimacy in modifying state of an object directly when obtaining 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 exceeds the boundaries of the encapsulation of a record originating from a SGBD, in which consistency is mandatory for that context, the above example would not have Constraint in the database with the UF table, ie encapsulation of the information was arbitrarily affected by an advisory method.

So why is it possible to map an advisory method?

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

  • It really is an excellent example to use mapping in methods for access.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.