Java hibernate实体中的必填字段
我有一个Personbean,带有必填的ssn和性别字段Java hibernate实体中的必填字段,java,hibernate,reflection,Java,Hibernate,Reflection,我有一个Personbean,带有必填的ssn和性别字段 @Entity public class Person { @Id private Long id; @NotNull private String ssn;//This is mandatory @NotNull private Gender gender;//This is mandatory private String firstname; private Date
@Entity
public class Person {
@Id
private Long id;
@NotNull
private String ssn;//This is mandatory
@NotNull
private Gender gender;//This is mandatory
private String firstname;
private Date dateOfBirth;
...
}
我所在的类MandatoryFieldsFinder没有访问person对象的权限,有没有办法在hibernate运行时或使用反射查找这些必填字段?我是一个完全的反思新手,不想使用它
public class MandatoryFieldsFinder{
public list getAllMandatoryFieldsFromPerson(){
....
//I need to find the mandatory fields in Person class here
...
}
}
您可以查询字段上是否存在批注:
// walk through fields
for (Field field : extractFields(target)) {
final InjectView annotation = field.getAnnotation(InjectView.class);
if (annotation != null) {
。。。做任何必要的事
}
}
如果您想在运行时执行此操作,唯一的方法就是使用反射(当您掌握了窍门时,它实际上非常有趣!)。一个简单实用的方法,如以下所示,可以做到这一点:
/**
* Gets a List of fields from the class that have the supplied annotation.
*
* @param clazz
* the class to inspect
* @param annotation
* the annotation to look for
* @return the List of fields with the annotation
*/
public static List<Field> getAnnotatedFields(Class<?> clazz,
Class<? extends Annotation> annotation) {
List<Field> annotatedFields = new ArrayList<Field>();
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(annotation)) {
annotatedFields.add(field);
}
}
return annotatedFields;
}
但请注意,并非所有注释都在运行时可用-这取决于它们的特性。如果@NotNull
具有运行时
的保留策略,那么就可以了,否则您必须在编译时执行一些操作
我想知道为什么您首先需要这些信息——JSR303 bean验证通常会为您提供这些信息。我需要这些信息的一个原因是在客户端为所需字段自动设置JS验证。
getAnnotatedFields(MyClass.class, NotNull.class)