您需要使用Annotation use-site targets,因为当有多个选项可用时,构造函数中声明的属性的默认目标是构造函数parameter上的注释,而不是getter(兼容JavaBeans的主机将看到getter).在这里使用data
类也可能不合适(see note at end).
@Entity data class User(
@Id
@GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)
var id: Long? = null,
@get:Size(min=5, max=15) // added annotation use-site target here
val name: String
)
The 所有物
target from the Kotlin docs may look tempting, but it can only be seen from Kotlin and not Java. Usually get
does the trick, and it is not needed on the bean set
.
The docs describe the process as:
如果未指定使用站点目标,则将根据所用注释的@target注释 Select 目标.如果存在多个适用目标,则使用以下列表中的第一个适用目标:
And the @Size
annotation is:
@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
Therefore since PARAMETER
is a valid target, and multiple targets are available (parameter, field, method [get/set]) it choses PARAMETER
which is not what you want. Therefore for a JavaBean host to see the 所有物 it will look for the getter (properties are defined by the getter/setter and not the backing field).
在其中一个Java samples个例子中,它显示:
public class Book {
private String title;
private String description;
// ...
@NotEmpty(groups={FirstLevelCheck.class, Default.class})
@Size(max=30)
public String getTitle() {
return title;
}
// ...
}
Which matches our usage of having it on the getter. If it were to be on the field like some of the validation annotations show, see the field
use-site target. Or if the field must also be publicly accessible, see the @JvmField annotation in Kotlin.
NOTE: As mentioned in notes from others, you should likely consider NOT using a 101 class for entities if they use an auto-generated ID since it will not exist for new objects the same as for retrieved objects; and a 101 class will generate 103 and 104 to include all fields including the ones it should not. You can read guidance about this from the 100.