根据反射得到一个hibernate实体的主键

来源:互联网 发布:淘宝运费价格怎么写 编辑:程序博客网 时间:2024/05/22 10:47

在很多地方都需要知道实体的名字,以便于抽象类对具体类的统一处理。如果设计时所有实体统一使用id,那就可以避免不必要的麻烦,否则如果有的实体PK叫id,有的实体PK叫userid,那在做sql语句统一操作时就比较麻烦了,硬编码是我们应该避免的。所以这里提供了一段小程序,供抽取那些使用annotation的实体pk。

 

 

 public static String getPKName(Class entityClass) {
  Field[] fields = entityClass.getDeclaredFields();

  for (Field f : fields) {
   Annotation[] annotations = f.getAnnotations();
   if (annotations.length <= 0) {
    String name = f.getName();
    String setMethodName = "get"
      + StringUtils.left(name, 1).toUpperCase()
      + StringUtils.substring(name, 1);
    try {
     Method method = entityClass
       .getDeclaredMethod(setMethodName);
     annotations = method.getAnnotations();
    } catch (Exception e) {
     // do nothing.
    }
   }
   for (Annotation anno : annotations) {
    if (anno.toString().contains("@javax.persistence.Id()"))
     return f.getName();
   }
  }

  return null;
 }