一种(不是那么简单)的方法是扫描您的实体类的字段
@OneToMany或带
@ManyToMany注释的字段并执行检查,以便可以向用户提供简洁的错误消息。以下示例代码假定您仅注释字段,而不注释getters方法,例如:
public class Person { @oneToMany(..) private List<House> houses; //...}首先使用反射获取所有字段的列表:
Fields[] fields = Person.class.getDeclaredFields();
然后迭代并检查
@OneToMany或
@ManyToMany注释
for(Field f : fields) { if( f.getAnnotation(OneToMany.class) != null || f.getAnnotation(ManyToMany.class) != null) { // Here you know f has to be checked before the person is deleted ... }}特定人员对象的字段值可以使用以下方法获得:
Person p = // fetch a person ..Field f = // assume f is the "List<House> houses" fieldList<House> houses = (List<House>) f.get(p);



