Annotations: methods versus variables

I was always sure (I don’t know why) that it’s better to add annotations to the variables, but when viewing the Hibernate document http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection I noticed that they tend to comment on methods. Therefore, I have to put my annotations before the methods, for example:

@Entity
public class Flight implements Serializable {
private long id;

@Id @GeneratedValue
public long getId() { return id; }

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

Or better to do it like this:

@Entity
public class Flight implements Serializable {
@Id @GeneratedValue
private long id;

public long getId() { return id; }

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

Or maybe there is no difference?

+5
source share
6 answers

As Peter points out, you need to choose one style and stick to it, as the style adopted for annotation @Idwill be used for everything.

, . , , . , Hibernate , , . , getter/setter (7 1 ), 99,9% ( , / ).

, , (, , , ).

+3

@Id : , Hibernate / /, -, Hibernate - .

, .

+2

.

, /, , . , , , , , .

+1

, , . , /, .

, / . , , ( ):

@Column(...)
private String email;

public String getAlias() { ... split email and return the part before @ ... }
public void setAlias( String alias ) { ... change the part before the @ ... }

public String getHost() { ... split email and return the part after @ ... }
public void setHost(String host) { ... change the part after the @... }

, , . . !

0

, . , - , , - , - .

0

, . . , USER, UserDetails Spring Security. , .

@Entity
class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @OneToMany
    private List<UserRole> roles;

    //....Setters and Getters..........
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }

If you put all annotations in the getters function, without displaying @OneToManyor @ManyToMany... it will work, but if you need to use this relationship, then Hibernate will break. I think Hibernate is already using annotation on top of the variable, so it doesn’t like annotating the top of functions for a consistent reason.

Thus, stick to what is common to the structure, you will not break your codes later.

0
source

All Articles