Spring中@Entity类中的注释顺序

时间:2018-02-28 15:07:42

标签: java spring jpa spring-boot annotations

可能听起来像一个有趣的问题,但我无法在其他地方找到答案:@Entity类的字段上的注释顺序是否重要?

我正在谈论像

这样的注释
@Column(name = "password")
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
@Transient
private String password;

@Column(name = "created_at", columnDefinition = "DATETIME")
@CreationTimestamp 
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;

2 个答案:

答案 0 :(得分:4)

从功能上讲,订单并不重要 从阅读的角度来看当然很重要 当你看一个实体领域时,你想直接了解一般情况。
例如,它在DB中的映射或使用的集合关系。

通常这个问题很重要,因为您需要为同一个字段声明一定数量的注释(至少为您的示例中的4个)。

一些有意义的想法:

  • 应在实体之间的代码中一致地指定它们
  • 使最常见的注释(@Column@ManyToOne等等)比最具体的注释(例如验证注释)更明显
  • 组相关注释。例如,应该对与验证相关的注释进行分组,同样也应该对与另一个实体的关联相关的注释进行分组。

从一般到具体和验证:

@Column(name = "pass")
@Transient
@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
private String password;

或者从具体到一般和验证:

@Length(min = 5, message = "*Your password must have at least 5 characters")
@NotEmpty(message = "*Please provide your password")
@Transient
@Column(name = "pass")
private String password;

作为凌乱的订单看起来更具可读性:

@Length(min = 5, message = "*Your password must have at least 5 characters")
@Column(name = "pass")
@Transient
@NotEmpty(message = "*Please provide your password")
private String password;

答案 1 :(得分:2)

通常最好遵循此表中建立的顺序:

http://www.oracle.com/technetwork/middleware/ias/toplink-jpa-annotations-096251.html

按照您的示例,它可能是:

@Column(name = "password")
@Transient
@NotEmpty(message = "*Please provide your password")
private String password;

@Column(name = "created_at", columnDefinition = "DATETIME")
@Temporal(TemporalType.TIMESTAMP)
@CreationTimestamp 
private Date createdAt;

但据我所知,没有既定的惯例