예제 #1
0
  public void addOrderBy(Class<?> clazz, String field, boolean ascending) {
    if (field == null) {
      return;
    }
    Field f;
    Pair<Class<?>, Field> pair = ReflectUtil.getAnyField(clazz, field);
    assert (pair != null) : "Can't find field " + field + " in " + clazz.getName();
    clazz = pair.first();
    f = pair.second();

    Column column = f.getAnnotation(Column.class);
    String name = column != null ? column.name() : field;

    StringBuilder order = new StringBuilder();
    if (column.table() == null || column.table().length() == 0) {
      order.append(DbUtil.getTableName(clazz));
    } else {
      order.append(column.table());
    }
    order.append(".").append(name).append(ascending ? " ASC " : " DESC ");

    if (_orderBy == null) {
      _orderBy = order.insert(0, " ORDER BY ").toString();
    } else {
      _orderBy = order.insert(0, _orderBy).toString();
    }
  }
예제 #2
0
파일: MyUtil.java 프로젝트: huangjp/myFrame
 /** 获得实体类中每个非Transient注解字段的连接串用于select * from语句中代替“*” */
 public static <T> String getTableField(Class<T> c) {
   Field[] fields = c.getDeclaredFields();
   StringBuilder sb = new StringBuilder();
   int i = 0;
   for (Field f : fields) {
     Column col = f.getAnnotation(Column.class);
     if (f.getAnnotation(Transient.class) == null) {
       i++;
       if (i == 1) {
         if (col != null) {
           sb.append("`" + col.name() + "`");
         } else {
           sb.append("`" + f.getName() + "`");
         }
       } else {
         if (col != null) {
           sb.append(", `" + col.name() + "`");
         } else {
           sb.append(",`" + f.getName() + "`");
         }
       }
     }
   }
   return sb.toString() == "" ? "*" : sb.toString();
 }
예제 #3
0
 /**
  * 根据MapData自动构建索引
  *
  * @param mapdata
  */
 public static void ReflectFillTheBean(MapBean mapdata, Document doc) {
   Method method[] = mapdata.getClass().getDeclaredMethods();
   for (int i = 0; i < method.length; i++) {
     if (method[i].getName().startsWith("get")) {
       // System.out.println(method[i].getName());
       Annotation[] an1 = method[i].getAnnotations();
       for (int j = 0; j < an1.length; j++) {
         if (an1[j] instanceof javax.persistence.Column) {
           javax.persistence.Column an11 = (javax.persistence.Column) an1[j];
           try {
             if (method[i].invoke(mapdata) != null)
               doc.add(
                   new Field(
                       an11.name(),
                       method[i].invoke(mapdata).toString(),
                       Field.Store.YES,
                       Field.Index.ANALYZED));
             //	System.out.println(an11.name()+">>>>>>>"+method[i].invoke(mapdata));
           } catch (IllegalArgumentException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           } catch (IllegalAccessException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           } catch (InvocationTargetException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           }
         }
       }
     }
   }
 }
예제 #4
0
파일: TUtils.java 프로젝트: imace/coffee
 /** 获取列名 */
 public static <T> String getColumnName(Class<T> clazz, String fieldName) {
   Column column = getColumn(clazz, fieldName);
   if (column != null) {
     return column.name();
   } else {
     return fieldName;
   }
 }
예제 #5
0
파일: TUtils.java 프로젝트: imace/coffee
 /** 判断列是否可为空 return : false-不可为空 ; true-可为空 */
 public static <T> boolean isNull(Class<T> clazz, String fieldName) {
   Column column = getColumn(clazz, fieldName);
   if (column != null) {
     return column.nullable();
   } else {
     return true;
   }
 }
예제 #6
0
 /**
  * シーケンスのデータ型を返します。
  *
  * @param propertyMeta プロパティメタデータ
  * @return シーケンスのデータ型
  */
 protected String getDataType(PropertyMeta propertyMeta) {
   ValueType valueType = valueTypeProvider.provide(propertyMeta);
   int sqlType = valueType.getSqlType();
   Column column = getColumn(propertyMeta);
   return dialect
       .getSqlType(sqlType)
       .getDataType(column.length(), column.precision(), column.scale(), false);
 }
 private Field columnNameToField(Class<?> clazz, String columnName) {
   for (Field field : clazz.getFields()) {
     Column column = field.getAnnotation(Column.class);
     if (equalsIgnoreCase(columnName, column.name())) {
       return field;
     }
   }
   return null;
 }
 private Method columnNameToMethod(Class<?> clazz, String columnName) {
   for (Method method : clazz.getMethods()) {
     Column column = method.getAnnotation(Column.class);
     if (column != null && equalsIgnoreCase(columnName, column.name())) {
       return method;
     }
   }
   return null;
 }
예제 #9
0
 private StringBuilder values() {
   StringBuilder sb = new StringBuilder();
   List<Column> columns = entityMeta.getNormalColumns();
   for (Column column : columns) {
     sb.append(column.name()).append("=?,");
   }
   sb.replace(sb.length() - 1, sb.length(), "");
   return sb;
 }
  /*
   * ************************************************************************
   * EDM Property Name - RULES
   * ************************************************************************
   * OData Property Names are represented in Camel Case. The first character
   * of JPA Attribute Name is converted to an UpperCase Character and set as
   * OData Property Name. JPA Attribute Name is set as Internal Name for OData
   * Property. The Column name (annotated as @Column(name="x")) is set as
   * column name in the mapping object.
   * ************************************************************************
   * EDM Property Name - RULES
   * ************************************************************************
   */
  public static void build(final JPAEdmPropertyView view, final boolean isComplexMode) {
    Attribute<?, ?> jpaAttribute = view.getJPAAttribute();
    String jpaAttributeName = jpaAttribute.getName();
    String propertyName = null;

    JPAEdmMappingModelAccess mappingModelAccess = view.getJPAEdmMappingModelAccess();
    if (mappingModelAccess != null && mappingModelAccess.isMappingModelExists()) {
      if (isComplexMode) {
        propertyName =
            mappingModelAccess.mapJPAEmbeddableTypeAttribute(
                view.getJPAEdmComplexTypeView()
                    .getJPAEmbeddableType()
                    .getJavaType()
                    .getSimpleName(),
                jpaAttributeName);
      } else {
        propertyName =
            mappingModelAccess.mapJPAAttribute(
                view.getJPAEdmEntityTypeView().getJPAEntityType().getName(), jpaAttributeName);
      }
    }
    if (propertyName == null) {
      propertyName =
          Character.toUpperCase(jpaAttributeName.charAt(0)) + jpaAttributeName.substring(1);
    }

    view.getEdmSimpleProperty().setName(propertyName);

    JPAEdmMapping mapping = new JPAEdmMappingImpl();
    ((Mapping) mapping).setInternalName(jpaAttributeName);

    AnnotatedElement annotatedElement = (AnnotatedElement) jpaAttribute.getJavaMember();
    if (annotatedElement != null) {
      Column column = annotatedElement.getAnnotation(Column.class);
      if (column != null) {
        mapping.setJPAColumnName(column.name());
      }
    } else {
      ManagedType<?> managedType = jpaAttribute.getDeclaringType();
      if (managedType != null) {
        Class<?> clazz = managedType.getJavaType();
        try {
          Field field = clazz.getDeclaredField(jpaAttributeName);
          Column column = field.getAnnotation(Column.class);
          if (column != null) {
            mapping.setJPAColumnName(column.name());
          }
        } catch (SecurityException e) {

        } catch (NoSuchFieldException e) {

        }
      }
    }
    view.getEdmSimpleProperty().setMapping((Mapping) mapping);
  }
예제 #11
0
 /**
  * 获取字段名,首先提取{@link javax.persistence.Column},如果不存在则使用属性名(的下划线形式)
  *
  * @param field
  * @return
  */
 private String getColumn(Field field) {
   Column column = field.getAnnotation(Column.class);
   String columnName;
   if (column != null) {
     columnName = column.name();
   } else {
     columnName = field.getName();
   }
   return columnName;
 }
 private String getIndexName(Field f, String alias) {
   if (f.isAnnotationPresent(Column.class)) {
     Column c = (Column) f.getAnnotation(Column.class);
     alias = c.name().trim();
     if (alias.isEmpty()) {
       alias = f.getName();
     }
   }
   return alias;
 }
예제 #13
0
 @SuppressWarnings({"rawtypes", "unchecked"})
 public static <X> X buildMockObject(Class<X> clazz) {
   X x = null;
   try {
     x = clazz.newInstance();
     for (Method method : clazz.getDeclaredMethods()) {
       String mn = method.getName();
       if (mn.startsWith("set")) {
         Class[] parameters = method.getParameterTypes();
         if (parameters.length == 1) {
           Method getMethod =
               MethodUtils.getAccessibleMethod(clazz, "get" + mn.substring(3), null);
           if (getMethod != null) {
             if (getMethod.getName().equals("getId")) {
               continue;
             }
             Object value = null;
             Class parameter = parameters[0];
             if (parameter.isAssignableFrom(String.class)) {
               Column column = getMethod.getAnnotation(Column.class);
               int columnLength = 32;
               if (column != null && column.length() < columnLength) {
                 columnLength = column.length();
               }
               Size size = getMethod.getAnnotation(Size.class);
               if (size != null && size.min() < columnLength) {
                 columnLength = size.min();
               }
               value = RandomStringUtils.randomAlphabetic(columnLength);
             } else if (parameter.isAssignableFrom(Date.class)) {
               value = new Date();
             } else if (parameter.isAssignableFrom(BigDecimal.class)) {
               value = new BigDecimal(new Random().nextDouble());
             } else if (parameter.isAssignableFrom(Integer.class)) {
               value = new Random().nextInt();
             } else if (parameter.isAssignableFrom(Boolean.class)) {
               value = new Random().nextBoolean();
             } else if (parameter.isEnum()) {
               Method m = parameter.getDeclaredMethod("values", null);
               Object[] result = (Object[]) m.invoke(parameter.getEnumConstants()[0], null);
               value = result[new Random().nextInt(result.length)];
             }
             if (value != null) {
               MethodUtils.invokeMethod(x, mn, value);
               logger.debug("{}={}", method.getName(), value);
             }
           }
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return x;
 }
예제 #14
0
  @SuppressWarnings("unchecked")
  public List<T> mapRersultSetToObject(ResultSet rs, Class outputClass) {
    List<T> outputList = null;
    try {
      // make sure resultset is not null
      if (rs != null) {
        // check if outputClass has 'Entity' annotation
        if (outputClass.isAnnotationPresent(Entity.class)) {
          // get the resultset metadata
          ResultSetMetaData rsmd = rs.getMetaData();
          // get all the attributes of outputClass
          Field[] fields = outputClass.getDeclaredFields();
          while (rs.next()) {
            T bean = (T) outputClass.newInstance();
            for (int _iterator = 0; _iterator < rsmd.getColumnCount(); _iterator++) {
              // getting the SQL column name
              String columnName = rsmd.getColumnName(_iterator + 1);
              // reading the value of the SQL column
              Object columnValue = rs.getObject(_iterator + 1);
              // iterating over outputClass attributes to check if any attribute has 'Column'
              // annotation with matching 'name' value
              for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                  Column column = field.getAnnotation(Column.class);
                  if (column.name().equalsIgnoreCase(columnName) && columnValue != null) {
                    BeanUtils.setProperty(bean, field.getName(), columnValue);
                    break;
                  }
                }
              }
            }
            if (outputList == null) {
              outputList = new ArrayList<T>();
            }
            outputList.add(bean);
          }

        } else {
          // throw some error
        }
      } else {
        return null;
      }
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
    return outputList;
  }
예제 #15
0
 /**
  * カラム記述を処理します。
  *
  * @param entityMeta エンティティメタデータ
  * @param propertyMetaList プロパティメタデータのリスト
  * @param tableDesc テーブル記述
  * @param generator テーブルジェネレータ
  */
 protected void doValueColumn(
     EntityMeta entityMeta, TableDesc tableDesc, TableGenerator generator) {
   String valueColumnName = generator.valueColumnName();
   if (StringUtil.isEmpty(valueColumnName)) {
     valueColumnName = TableIdGenerator.DEFAULT_VALUE_COLUMN_NAME;
   }
   ColumnDesc columnDesc = new ColumnDesc();
   columnDesc.setName(valueColumnName);
   SqlType sqlType = dialect.getSqlType(Types.BIGINT);
   columnDesc.setSqlType(sqlType);
   Column column = AnnotationUtil.getDefaultColumn();
   columnDesc.setDefinition(sqlType.getDataType(0, column.precision(), 0, false));
   columnDesc.setNullable(false);
   tableDesc.addColumnDesc(columnDesc);
 }
 private List<String> validateSimpleUniqueConstraintsDefinedOnFields(Identifiable<?> entity) {
   Class<?> entityClass = getClassWithoutInitializingProxy(entity);
   List<String> errors = newArrayList();
   for (Field field : entityClass.getFields()) {
     Column column = field.getAnnotation(Column.class);
     if (column != null && column.unique()) {
       Map<String, Object> values = newHashMap();
       values.put(field.getName(), jpaUtil.getValueFromField(field, entity));
       if (existsInDatabaseOnAllObjects(entity, values)) {
         errors.add(simpleUniqueConstraintError(entity, field.getName()));
       }
     }
   }
   return errors;
 }
 private List<String> validateSimpleUniqueConstraintsDefinedOnMethods(Identifiable<?> entity) {
   Class<?> entityClass = getClassWithoutInitializingProxy(entity);
   List<String> errors = newArrayList();
   for (Method method : entityClass.getMethods()) {
     Column column = entityClass.getAnnotation(Column.class);
     if (column != null && column.unique()) {
       Map<String, Object> values = newHashMap();
       String property = jpaUtil.methodToProperty(method);
       values.put(property, invokeMethod(method, entity));
       if (existsInDatabaseOnAllObjects(entity, values)) {
         errors.add(simpleUniqueConstraintError(entity, property));
       }
     }
   }
   return errors;
 }
예제 #18
0
 /**
  * 获取可以做全文检索的字段
  *
  * @param mapdata
  * @return
  */
 public static String[] getQueryFeild(MapBean mapdata) {
   ArrayList<String> feild = new ArrayList<String>();
   Method method[] = mapdata.getClass().getDeclaredMethods();
   for (int i = 0; i < method.length; i++) {
     if (method[i].getName().startsWith("get")) {
       Annotation[] an1 = method[i].getAnnotations();
       for (int j = 0; j < an1.length; j++) {
         if (an1[j] instanceof javax.persistence.Column) {
           javax.persistence.Column an11 = (javax.persistence.Column) an1[j];
           feild.add(an11.name());
         }
       }
     }
   }
   return feild.toArray(new String[feild.size()]);
 }
예제 #19
0
  /**
   * 主キー記述を処理します。
   *
   * @param entityMeta エンティティメタデータ
   * @param propertyMeta プロパティメタデータ
   * @param tableDesc テーブル記述
   * @param generator テーブルジェネレータ
   */
  protected void doPrimaryKeyColumn(
      EntityMeta entityMeta, TableDesc tableDesc, TableGenerator generator) {
    String pkColumnName = generator.pkColumnName();
    if (StringUtil.isEmpty(pkColumnName)) {
      pkColumnName = TableIdGenerator.DEFAULT_PK_COLUMN_NAME;
    }
    PrimaryKeyDesc primaryKeyDesc = new PrimaryKeyDesc();
    primaryKeyDesc.addColumnName(pkColumnName);
    tableDesc.setPrimaryKeyDesc(primaryKeyDesc);

    ColumnDesc columnDesc = new ColumnDesc();
    columnDesc.setName(pkColumnName);
    SqlType sqlType = dialect.getSqlType(Types.VARCHAR);
    columnDesc.setSqlType(sqlType);
    Column column = AnnotationUtil.getDefaultColumn();
    columnDesc.setDefinition(sqlType.getDataType(column.length(), 0, 0, false));
    tableDesc.addColumnDesc(columnDesc);
  }
예제 #20
0
  /**
   * No checking on the annotations - client could get unpredictable behaviour if annotations aren't
   * configured properly.
   *
   * @return
   */
  public void discover() {

    jpaEntity = entityClass.isAnnotationPresent(javax.persistence.Entity.class);
    Table table = (Table) entityClass.getAnnotation(Table.class);
    if (!jpaEntity || table == null)
      throw new UnsupportedOperationException(); // throw a more appropriate exception

    tableName = table.name();

    // Absolutely no validation annotation parsing!!
    // this will ALWAYS parse annotations in this order: ID, EmbeddedId, and Column

    Field[] fields = entityClass.getDeclaredFields();
    for (Field f : fields) {

      // first Id annotation
      Annotation fan = f.getAnnotation(Id.class);
      if (fan != null) {
        Column col = (Column) f.getAnnotation(Column.class);
        idMapping = new ColumnMapping(col.name(), f);
        continue;
      }

      // Embedded ID
      fan = f.getAnnotation(EmbeddedId.class);
      if (fan != null) {

        ArrayList<ColumnMapping> emList = new ArrayList<>();

        for (Field inF : f.getType().getDeclaredFields()) {
          if (inF.getAnnotation(Column.class) != null) {
            Column innerId = (Column) inF.getAnnotation(Column.class);
            // put column name in lower case as driver does
            emList.add(new ColumnMapping(innerId.name().toLowerCase(), inF));
          }
        }
        // column name
        embedded = new Embedded(f, emList.toArray(emptyColArr));

        continue;
      }
      // finally get the column
      // there's special handling for map type - which is a definite area for improvement

      fan = f.getAnnotation(Column.class);
      if (fan != null) {
        Column col = (Column) fan;
        ColumnMapping mapping = new ColumnMapping(col.name(), f);
        // special consideration for map
        if (Map.class.isAssignableFrom(f.getType())) {
          mapping.isMap = true;
        }
        // put in lower case as the driver
        colsToFields.put(col.name().toLowerCase(), mapping);

        continue;
      }
    }
  }
예제 #21
0
  /**
   * Apply the annotations on the field or getter method to the property.
   *
   * @throws IllegalAccessException
   * @throws InstantiationException
   */
  private void applyAnnotations(Property prop, AnnotatedElement ae)
      throws InstantiationException, IllegalAccessException {

    Column col = ae.getAnnotation(Column.class);
    if (col != null) {
      String name = col.name().trim();
      if (name.length() > 0) {
        prop.name = name;
      }
      prop.columnAnnotation = col;
    }

    if (ae.getAnnotation(Id.class) != null) {
      prop.isPrimaryKey = true;
      primaryKeyName = prop.name;
    }

    if (ae.getAnnotation(GeneratedValue.class) != null) {
      generatedColumnName = prop.name;
      prop.isGenerated = true;
    }

    if (prop.dataType.isEnum()) {
      prop.isEnumField = true;
      prop.enumClass = (Class<Enum>) prop.dataType;
      /* We default to STRING enum type. Can be overriden with @Enumerated annotation */
      prop.enumType = EnumType.STRING;
      if (ae.getAnnotation(Enumerated.class) != null) {
        prop.enumType = ae.getAnnotation(Enumerated.class).value();
      }
    }

    DbSerializer sc = ae.getAnnotation(DbSerializer.class);
    if (sc != null) {
      prop.serializer = sc.value().newInstance();
    }
  }
예제 #22
0
  public static Map<String, UiConfigImpl> getUiConfigs(Class<?> entityClass) {
    Map<String, UiConfigImpl> map = cache.get(entityClass);
    if (map == null || AppInfo.getStage() == Stage.DEVELOPMENT) {
      GenericGenerator genericGenerator =
          AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(
                  entityClass, GenericGenerator.class)
              .get("id");
      boolean idAssigned =
          genericGenerator != null && "assigned".equals(genericGenerator.strategy());
      Map<String, NaturalId> naturalIds =
          AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(entityClass, NaturalId.class);
      Set<String> hides = new HashSet<String>();
      map = new HashMap<String, UiConfigImpl>();
      PropertyDescriptor[] pds =
          org.springframework.beans.BeanUtils.getPropertyDescriptors(entityClass);
      for (PropertyDescriptor pd : pds) {
        String propertyName = pd.getName();
        if (pd.getReadMethod() == null
            || pd.getWriteMethod() == null
                && pd.getReadMethod().getAnnotation(UiConfig.class) == null) continue;
        Class<?> declaredClass = pd.getReadMethod().getDeclaringClass();
        Version version = pd.getReadMethod().getAnnotation(Version.class);
        if (version == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) version = f.getAnnotation(Version.class);
          } catch (Exception e) {
          }
        if (version != null) continue;
        Transient trans = pd.getReadMethod().getAnnotation(Transient.class);
        if (trans == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) trans = f.getAnnotation(Transient.class);
          } catch (Exception e) {
          }
        SearchableProperty searchableProperty =
            pd.getReadMethod().getAnnotation(SearchableProperty.class);
        if (searchableProperty == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) searchableProperty = f.getAnnotation(SearchableProperty.class);
          } catch (Exception e) {
          }
        SearchableId searchableId = pd.getReadMethod().getAnnotation(SearchableId.class);
        if (searchableId == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) searchableId = f.getAnnotation(SearchableId.class);
          } catch (Exception e) {
          }
        UiConfig uiConfig = pd.getReadMethod().getAnnotation(UiConfig.class);
        if (uiConfig == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) uiConfig = f.getAnnotation(UiConfig.class);
          } catch (Exception e) {
          }

        if (uiConfig != null && uiConfig.hidden()) continue;
        if ("new".equals(propertyName)
            || !idAssigned && "id".equals(propertyName)
            || "class".equals(propertyName)
            || "fieldHandler".equals(propertyName)
            || pd.getReadMethod() == null
            || hides.contains(propertyName)) continue;
        Column columnannotation = pd.getReadMethod().getAnnotation(Column.class);
        if (columnannotation == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) columnannotation = f.getAnnotation(Column.class);
          } catch (Exception e) {
          }
        Basic basic = pd.getReadMethod().getAnnotation(Basic.class);
        if (basic == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) basic = f.getAnnotation(Basic.class);
          } catch (Exception e) {
          }
        Lob lob = pd.getReadMethod().getAnnotation(Lob.class);
        if (lob == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) lob = f.getAnnotation(Lob.class);
          } catch (Exception e) {
          }
        UiConfigImpl uci = new UiConfigImpl(pd.getPropertyType(), uiConfig);
        if (idAssigned && propertyName.equals("id")) uci.addCssClass("required checkavailable");
        if (Attributable.class.isAssignableFrom(entityClass) && pd.getName().equals("attributes")) {
          uci.setType("attributes");
        }
        if (trans != null) {
          uci.setExcludedFromCriteria(true);
          uci.setExcludedFromLike(true);
          uci.setExcludedFromOrdering(true);
        }
        if (lob != null) {
          uci.setExcludedFromCriteria(true);
          if (uci.getMaxlength() == 0) uci.setMaxlength(2 * 1024 * 1024);
        }
        if (columnannotation != null && !columnannotation.nullable()
            || basic != null && !basic.optional()) uci.setRequired(true);
        if (columnannotation != null && columnannotation.length() != 255 && uci.getMaxlength() == 0)
          uci.setMaxlength(columnannotation.length());
        if (lob != null || uci.getMaxlength() > 255) uci.setExcludedFromOrdering(true);
        Class<?> returnType = pd.getPropertyType();
        if (returnType.isEnum()) {
          uci.setType("enum");
          try {
            returnType.getMethod("getName");
            uci.setListKey("name");
          } catch (NoSuchMethodException e) {
            uci.setListKey("top");
          }
          try {
            returnType.getMethod("getDisplayName");
            uci.setListValue("displayName");
          } catch (NoSuchMethodException e) {
            uci.setListValue(uci.getListKey());
          }
          map.put(propertyName, uci);
          continue;
        } else if (Persistable.class.isAssignableFrom(returnType)) {
          JoinColumn joincolumnannotation = pd.getReadMethod().getAnnotation(JoinColumn.class);
          if (joincolumnannotation == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) joincolumnannotation = f.getAnnotation(JoinColumn.class);
            } catch (Exception e) {
            }
          if (joincolumnannotation != null && !joincolumnannotation.nullable())
            uci.setRequired(true);
          ManyToOne manyToOne = pd.getReadMethod().getAnnotation(ManyToOne.class);
          if (manyToOne == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) manyToOne = f.getAnnotation(ManyToOne.class);
            } catch (Exception e) {
            }
          if (manyToOne != null && !manyToOne.optional()) uci.setRequired(true);
          uci.setType("listpick");
          uci.setExcludeIfNotEdited(true);
          if (StringUtils.isBlank(uci.getPickUrl())) {
            String url = AutoConfigPackageProvider.getEntityUrl(returnType);
            StringBuilder sb =
                url != null
                    ? new StringBuilder(url)
                    : new StringBuilder("/")
                        .append(StringUtils.uncapitalize(returnType.getSimpleName()));
            sb.append("/pick");
            Set<String> columns = new LinkedHashSet<String>();
            columns.addAll(
                AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(returnType, NaturalId.class)
                    .keySet());
            Map<String, UiConfigImpl> configs = getUiConfigs(returnType);
            for (String column : "fullname,name,code".split(","))
              if (configs.containsKey(column)
                  && (!columns.contains("fullname") && column.equals("name")
                      || !column.equals("name"))) columns.add(column);
            for (Map.Entry<String, UiConfigImpl> entry : configs.entrySet())
              if (entry.getValue().isShownInPick()) columns.add(entry.getKey());
            if (!columns.isEmpty()) {
              sb.append("?columns=" + StringUtils.join(columns, ','));
            }
            uci.setPickUrl(sb.toString());
          }
          map.put(propertyName, uci);
          continue;
        }
        if (returnType == Integer.TYPE
            || returnType == Short.TYPE
            || returnType == Long.TYPE
            || returnType == Double.TYPE
            || returnType == Float.TYPE
            || Number.class.isAssignableFrom(returnType)) {
          if (returnType == Integer.TYPE
              || returnType == Integer.class
              || returnType == Short.TYPE
              || returnType == Short.class) {
            uci.setInputType("number");
            uci.addCssClass("integer");

          } else if (returnType == Long.TYPE || returnType == Long.class) {
            uci.setInputType("number");
            uci.addCssClass("long");
          } else if (returnType == Double.TYPE
              || returnType == Double.class
              || returnType == Float.TYPE
              || returnType == Float.class
              || returnType == BigDecimal.class) {
            uci.setInputType("number");
            uci.addCssClass("double");
          }
          Set<String> cssClasses = uci.getCssClasses();
          if (cssClasses.contains("double") && !uci.getDynamicAttributes().containsKey("step"))
            uci.getDynamicAttributes().put("step", "0.01");
          if (cssClasses.contains("positive") && !uci.getDynamicAttributes().containsKey("min")) {
            uci.getDynamicAttributes().put("min", "1");
            if (cssClasses.contains("double")) uci.getDynamicAttributes().put("min", "0.01");
            if (cssClasses.contains("zero")) uci.getDynamicAttributes().put("min", "0");
          }
        } else if (Date.class.isAssignableFrom(returnType)) {
          Temporal temporal = pd.getReadMethod().getAnnotation(Temporal.class);
          if (temporal == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) temporal = f.getAnnotation(Temporal.class);
            } catch (Exception e) {
            }
          String temporalType = "date";
          if (temporal != null)
            if (temporal.value() == TemporalType.TIMESTAMP) temporalType = "datetime";
            else if (temporal.value() == TemporalType.TIME) temporalType = "time";
          uci.addCssClass(temporalType);
          // uci.setInputType(temporalType);
          if (StringUtils.isBlank(uci.getCellEdit())) uci.setCellEdit("click," + temporalType);
        } else if (String.class == returnType
            && pd.getName().toLowerCase().contains("email")
            && !pd.getName().contains("Password")) {
          uci.setInputType("email");
          uci.addCssClass("email");
        } else if (returnType == Boolean.TYPE || returnType == Boolean.class) {
          uci.setType("checkbox");
        }
        if (columnannotation != null && columnannotation.unique()) uci.setUnique(true);
        if (searchableProperty != null || searchableId != null) uci.setSearchable(true);

        if (naturalIds.containsKey(pd.getName())) {
          uci.setRequired(true);
          if (naturalIds.size() == 1) uci.addCssClass("checkavailable");
        }
        map.put(propertyName, uci);
      }
      List<Map.Entry<String, UiConfigImpl>> list =
          new ArrayList<Map.Entry<String, UiConfigImpl>>(map.entrySet());
      Collections.sort(list, comparator);
      Map<String, UiConfigImpl> sortedMap = new LinkedHashMap<String, UiConfigImpl>();
      for (Map.Entry<String, UiConfigImpl> entry : list)
        sortedMap.put(entry.getKey(), entry.getValue());
      map = sortedMap;
      cache.put(entityClass, Collections.unmodifiableMap(map));
    }
    return map;
  }
예제 #23
0
  @SuppressWarnings({"resource", "rawtypes", "unchecked"})
  public static void main(String[] args) throws Exception {
    Configuration cfg = new Configuration();
    // 设置FreeMarker的模版文件位置
    cfg.setClassForTemplateLoading(
        SourceCodeFrameworkBuilder.class, "/lab/s2jh/tool/builder/freemarker");
    cfg.setDefaultEncoding("UTF-8");
    String rootPath = args[0];

    Set<String> entityNames = new HashSet<String>();

    String entityListFile = rootPath + "entity_list.properties";
    BufferedReader reader = new BufferedReader(new FileReader(entityListFile));
    String line;
    while ((line = reader.readLine()) != null) {
      if (StringUtils.isNotBlank(line) && !line.startsWith("#")) {
        entityNames.add(line);
      }
    }

    new File(rootPath + "\\codes").mkdir();
    new File(rootPath + "\\codes\\integrate").mkdir();
    new File(rootPath + "\\codes\\standalone").mkdir();

    for (String entityName : entityNames) {

      String integrateRootPath = rootPath + "\\codes\\integrate\\";
      String standaloneRootPath = rootPath + "\\codes\\standalone\\";

      String rootPackage = StringUtils.substringBetween(entityName, "[", "]");
      String rootPackagePath = StringUtils.replace(rootPackage, ".", "\\");

      String className = StringUtils.substringAfterLast(entityName, ".");
      String classFullName =
          StringUtils.replaceEach(entityName, new String[] {"[", "]"}, new String[] {"", ""});

      String modelName = StringUtils.substringBetween(entityName, "].", ".entity");
      String modelPath = StringUtils.replace(modelName, ".", "/");
      modelPath = "/" + modelPath;
      String modelPackagePath = StringUtils.replace(modelName, ".", "\\");
      modelPackagePath = "\\" + modelPackagePath;

      Map<String, Object> root = new HashMap<String, Object>();
      String nameField = propertyToField(StringUtils.uncapitalize(className)).toLowerCase();
      root.put("model_name", modelName);
      root.put("model_path", modelPath);
      root.put("entity_name", className);
      root.put("entity_name_uncapitalize", StringUtils.uncapitalize(className));
      root.put("entity_name_field", nameField);
      root.put("root_package", rootPackage + "." + modelName);
      root.put("action_package", rootPackage);
      root.put("table_name", "T_TODO_" + className.toUpperCase());
      root.put("base", "${base}");
      Class entityClass = Class.forName(classFullName);
      root.put("id_type", entityClass.getMethod("getId").getReturnType().getSimpleName());
      MetaData classEntityComment = (MetaData) entityClass.getAnnotation(MetaData.class);
      if (classEntityComment != null) {
        root.put("model_title", classEntityComment.value());
      } else {
        root.put("model_title", entityName);
      }
      debug("Entity Data Map=" + root);

      Set<Field> fields = new HashSet<Field>();

      Field[] curfields = entityClass.getDeclaredFields();
      for (Field field : curfields) {
        fields.add(field);
      }

      Class superClass = entityClass.getSuperclass();
      while (superClass != null && !superClass.equals(BaseEntity.class)) {
        Field[] superfields = superClass.getDeclaredFields();
        for (Field field : superfields) {
          fields.add(field);
        }
        superClass = superClass.getSuperclass();
      }

      // 定义用于OneToOne关联对象的Fetch参数
      Map<String, String> fetchJoinFields = Maps.newHashMap();
      List<EntityCodeField> entityFields = new ArrayList<EntityCodeField>();
      int cnt = 1;
      for (Field field : fields) {
        if ((field.getModifiers() & Modifier.FINAL) != 0 || "id".equals(field.getName())) {
          continue;
        }
        debug(" - Field=" + field);
        Class fieldType = field.getType();

        EntityCodeField entityCodeField = null;
        if (fieldType.isEnum()) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(80);
          entityCodeField.setListAlign("center");
        } else if (fieldType == Boolean.class) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(60);
          entityCodeField.setListAlign("center");
        } else if (PersistableEntity.class.isAssignableFrom(fieldType)) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setFieldType("Entity");

        } else if (Number.class.isAssignableFrom(fieldType)) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);
          entityCodeField.setListWidth(60);
          entityCodeField.setListAlign("right");
        } else if (fieldType == String.class) {
          entityCodeField = new EntityCodeField();

          // 根据Hibernate注解的字符串类型和长度设定是否列表显示
          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          Column fieldColumn = getMethod.getAnnotation(Column.class);
          if (fieldColumn != null) {
            int length = fieldColumn.length();
            if (length > 255) {
              entityCodeField.setList(false);
              entityCodeField.setListWidth(length);
            }
          }
          Lob fieldLob = getMethod.getAnnotation(Lob.class);
          if (fieldLob != null) {
            entityCodeField.setList(false);
            entityCodeField.setListWidth(Integer.MAX_VALUE);
          }
        } else if (fieldType == Date.class) {
          entityCodeField = new EntityCodeField();
          entityCodeField.setListFixed(true);

          // 根据Json注解设定合理的列宽
          entityCodeField.setListWidth(120);
          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          JsonSerialize fieldJsonSerialize = getMethod.getAnnotation(JsonSerialize.class);
          if (fieldJsonSerialize != null) {
            if (DateJsonSerializer.class.equals(fieldJsonSerialize.using())) {
              entityCodeField.setListWidth(80);
            }
          }
          entityCodeField.setListAlign("center");
        }

        if (entityCodeField != null) {
          if (fieldType.isEnum()) {
            entityCodeField.setEnumField(true);
          }
          if (StringUtils.isBlank(entityCodeField.getFieldType())) {
            entityCodeField.setFieldType(fieldType.getSimpleName());
          }
          entityCodeField.setFieldName(field.getName());
          EntityAutoCode entityAutoCode = field.getAnnotation(EntityAutoCode.class);
          if (entityAutoCode != null) {
            entityCodeField.setListHidden(entityAutoCode.listHidden());
            entityCodeField.setEdit(entityAutoCode.edit());
            entityCodeField.setList(entityAutoCode.listHidden() || entityAutoCode.listShow());
            entityCodeField.setOrder(entityAutoCode.order());
          } else {
            entityCodeField.setTitle(field.getName());
            entityCodeField.setOrder(cnt++);
          }

          MetaData entityMetaData = field.getAnnotation(MetaData.class);
          if (entityMetaData != null) {
            entityCodeField.setTitle(entityMetaData.value());
          }

          Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName()));
          JsonProperty fieldJsonProperty = getMethod.getAnnotation(JsonProperty.class);
          if (fieldJsonProperty != null) {
            entityCodeField.setList(true);
          }

          if (entityCodeField.getList() || entityCodeField.getListHidden()) {
            JoinColumn fieldJoinColumn = getMethod.getAnnotation(JoinColumn.class);
            if (fieldJoinColumn != null) {
              if (fieldJoinColumn.nullable() == false) {
                fetchJoinFields.put(field.getName(), "INNER");
              } else {
                fetchJoinFields.put(field.getName(), "LEFT");
              }
            }
          }

          entityFields.add(entityCodeField);
        }
      }
      Collections.sort(entityFields);
      root.put("entityFields", entityFields);
      if (fetchJoinFields.size() > 0) {
        root.put("fetchJoinFields", fetchJoinFields);
      }

      integrateRootPath = integrateRootPath + rootPackagePath + modelPackagePath;
      // process(cfg.getTemplate("Entity.ftl"), root, integrateRootPath + "\\entity\\", className +
      // ".java");
      process(
          cfg.getTemplate("Dao.ftl"), root, integrateRootPath + "\\dao\\", className + "Dao.java");
      process(
          cfg.getTemplate("Service.ftl"),
          root,
          integrateRootPath + "\\service\\",
          className + "Service.java");
      process(
          cfg.getTemplate("Controller.ftl"),
          root,
          integrateRootPath + "\\web\\action\\",
          className + "Controller.java");
      process(
          cfg.getTemplate("Test.ftl"),
          root,
          integrateRootPath + "\\test\\service\\",
          className + "ServiceTest.java");
      process(
          cfg.getTemplate("JSP_Index.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-index.jsp");
      process(
          cfg.getTemplate("JSP_Input_Tabs.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-inputTabs.jsp");
      process(
          cfg.getTemplate("JSP_Input_Basic.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-inputBasic.jsp");
      process(
          cfg.getTemplate("JSP_View_Tabs.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-viewTabs.jsp");
      process(
          cfg.getTemplate("JSP_View_Basic.ftl"),
          root,
          integrateRootPath + "\\jsp\\",
          nameField + "-viewBasic.jsp");

      standaloneRootPath =
          standaloneRootPath + rootPackagePath + modelPackagePath + "\\" + className;
      // process(cfg.getTemplate("Entity.ftl"), root, standaloneRootPath + "\\entity\\", className +
      // ".java");
      process(
          cfg.getTemplate("Dao.ftl"), root, standaloneRootPath + "\\dao\\", className + "Dao.java");
      process(
          cfg.getTemplate("Service.ftl"),
          root,
          standaloneRootPath + "\\service\\",
          className + "Service.java");
      process(
          cfg.getTemplate("Controller.ftl"),
          root,
          standaloneRootPath + "\\web\\action\\",
          className + "Controller.java");
      process(
          cfg.getTemplate("Test.ftl"),
          root,
          standaloneRootPath + "\\test\\service\\",
          className + "ServiceTest.java");
      process(
          cfg.getTemplate("JSP_Index.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-index.jsp");
      process(
          cfg.getTemplate("JSP_Input_Tabs.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-inputTabs.jsp");
      process(
          cfg.getTemplate("JSP_Input_Basic.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-inputBasic.jsp");
      process(
          cfg.getTemplate("JSP_View_Tabs.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-viewTabs.jsp");
      process(
          cfg.getTemplate("JSP_View_Basic.ftl"),
          root,
          standaloneRootPath + "\\jsp\\",
          nameField + "-viewBasic.jsp");
    }
  }
  private void readColumn(Column columnAnn, DeployBeanProperty prop) {

    if (!isEmpty(columnAnn.name())) {
      String dbColumn = databasePlatform.convertQuotedIdentifiers(columnAnn.name());
      prop.setDbColumn(dbColumn);
    }

    prop.setDbInsertable(columnAnn.insertable());
    prop.setDbUpdateable(columnAnn.updatable());
    prop.setNullable(columnAnn.nullable());
    prop.setUnique(columnAnn.unique());
    if (columnAnn.precision() > 0) {
      prop.setDbLength(columnAnn.precision());
    } else if (columnAnn.length() != 255) {
      // set default 255 on DbTypeMap
      prop.setDbLength(columnAnn.length());
    }
    prop.setDbScale(columnAnn.scale());
    prop.setDbColumnDefn(columnAnn.columnDefinition());

    String baseTable = descriptor.getBaseTable();
    String tableName = columnAnn.table();
    if (tableName.equals("") || tableName.equalsIgnoreCase(baseTable)) {
      // its a base table property...
    } else {
      // its on a secondary table...
      prop.setSecondaryTable(tableName);
      // DeployTableJoin tableJoin = info.getTableJoin(tableName);
      // tableJoin.addProperty(prop);
    }
  }
  private void searchForRevisionInfoCfgInProperties(
      XClass clazz,
      ReflectionManager reflectionManager,
      MutableBoolean revisionNumberFound,
      MutableBoolean revisionTimestampFound,
      MutableBoolean modifiedEntityNamesFound,
      String accessType) {
    for (XProperty property : clazz.getDeclaredProperties(accessType)) {
      RevisionNumber revisionNumber = property.getAnnotation(RevisionNumber.class);
      RevisionTimestamp revisionTimestamp = property.getAnnotation(RevisionTimestamp.class);
      ModifiedEntityNames modifiedEntityNames = property.getAnnotation(ModifiedEntityNames.class);

      if (revisionNumber != null) {
        if (revisionNumberFound.isSet()) {
          throw new MappingException("Only one property may be annotated with @RevisionNumber!");
        }

        XClass revisionNumberClass = property.getType();
        if (reflectionManager.equals(revisionNumberClass, Integer.class)
            || reflectionManager.equals(revisionNumberClass, Integer.TYPE)) {
          revisionInfoIdData =
              new PropertyData(property.getName(), property.getName(), accessType, null);
          revisionNumberFound.set();
        } else if (reflectionManager.equals(revisionNumberClass, Long.class)
            || reflectionManager.equals(revisionNumberClass, Long.TYPE)) {
          revisionInfoIdData =
              new PropertyData(property.getName(), property.getName(), accessType, null);
          revisionNumberFound.set();

          // The default is integer
          revisionPropType = "long";
        } else {
          throw new MappingException(
              "The field annotated with @RevisionNumber must be of type "
                  + "int, Integer, long or Long");
        }

        // Getting the @Column definition of the revision number property, to later use that info to
        // generate the same mapping for the relation from an audit table's revision number to the
        // revision entity revision number.
        Column revisionPropColumn = property.getAnnotation(Column.class);
        if (revisionPropColumn != null) {
          revisionPropSqlType = revisionPropColumn.columnDefinition();
        }
      }

      if (revisionTimestamp != null) {
        if (revisionTimestampFound.isSet()) {
          throw new MappingException("Only one property may be annotated with @RevisionTimestamp!");
        }

        XClass revisionTimestampClass = property.getType();
        if (reflectionManager.equals(revisionTimestampClass, Long.class)
            || reflectionManager.equals(revisionTimestampClass, Long.TYPE)
            || reflectionManager.equals(revisionTimestampClass, Date.class)
            || reflectionManager.equals(revisionTimestampClass, java.sql.Date.class)) {
          revisionInfoTimestampData =
              new PropertyData(property.getName(), property.getName(), accessType, null);
          revisionTimestampFound.set();
        } else {
          throw new MappingException(
              "The field annotated with @RevisionTimestamp must be of type "
                  + "long, Long, java.util.Date or java.sql.Date");
        }
      }

      if (modifiedEntityNames != null) {
        if (modifiedEntityNamesFound.isSet()) {
          throw new MappingException(
              "Only one property may be annotated with @ModifiedEntityNames!");
        }
        XClass modifiedEntityNamesClass = property.getType();
        if (reflectionManager.equals(modifiedEntityNamesClass, Set.class)
            && reflectionManager.equals(property.getElementClass(), String.class)) {
          modifiedEntityNamesData =
              new PropertyData(property.getName(), property.getName(), accessType, null);
          modifiedEntityNamesFound.set();
        } else {
          throw new MappingException(
              "The field annotated with @ModifiedEntityNames must be of Set<String> type.");
        }
      }
    }
  }
예제 #26
0
  /**
   * 解析字段定义<br>
   * <功能详细描述>
   *
   * @param type
   * @param pd
   * @return [参数说明]
   * @return JPAEntityColumnDef [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  private static JPAEntityColumnDef doAnalyzeCoumnDef(
      String tableName, Class<?> type, PropertyDescriptor pd) {
    JPAEntityColumnDef colDef = null;

    String columnComment = "";
    String propertyName = pd.getName();
    String columnName = propertyName;
    Class<?> javaType = pd.getPropertyType();
    int size = 0;
    int scale = 0;
    boolean required = false;

    // 获取字段
    Field field = FieldUtils.getField(type, propertyName, true);
    if (field != null) {
      if (field.isAnnotationPresent(Transient.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (field.isAnnotationPresent(OneToMany.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (field.isAnnotationPresent(Column.class)) {
        Column columnAnno = field.getAnnotation(Column.class);
        columnName = columnAnno.name();
        required = !columnAnno.nullable();
        size = Math.max(columnAnno.length(), columnAnno.precision());
        scale = columnAnno.scale();
      }
    }

    // 获取读方法
    Method readMethod = pd.getReadMethod();
    if (readMethod != null) {
      if (readMethod.isAnnotationPresent(Transient.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (readMethod.isAnnotationPresent(OneToMany.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (readMethod.isAnnotationPresent(Column.class)) {
        Column columnAnno = readMethod.getAnnotation(Column.class);
        columnName = columnAnno.name();
        required = !columnAnno.nullable();
        size = Math.max(columnAnno.length(), columnAnno.precision());
        scale = columnAnno.scale();
      }
    }

    JdbcTypeEnum jdbcType = JPAEntityTypeRegistry.getJdbcType(javaType); // 获取对应的jdbcType
    colDef = new JPAEntityColumnDef(columnName, javaType, jdbcType, size, scale, required);
    colDef.setComment(columnComment);
    return colDef;
  }
  /** Test version accessor methods: modifiers, arguments, annotations, and return types. */
  private void testVersionAccessors() {
    // skip classes that have a getVersion from a superclass
    if (!_entityClass.getSuperclass().equals(AbstractEntity.class)) {
      return;
    }

    org.hibernate.annotations.Entity entityAnnotation =
        _entityClass.getAnnotation(org.hibernate.annotations.Entity.class);
    if (entityAnnotation != null && !entityAnnotation.mutable()) {
      return;
    }
    if (_entityClass.getAnnotation(Immutable.class) != null) {
      return;
    }

    // getVersion
    try {
      Method getVersionMethod = _entityClass.getDeclaredMethod("getVersion");
      assertTrue(
          "private getVersion for " + _entityClass,
          Modifier.isPrivate(getVersionMethod.getModifiers()));
      assertFalse(
          "instance getVersion for " + _entityClass,
          Modifier.isStatic(getVersionMethod.getModifiers()));
      assertEquals(
          "getVersion return type for " + _entityClass,
          getVersionMethod.getReturnType(),
          Integer.class);

      Column column = getVersionMethod.getAnnotation(Column.class);
      assertNotNull("getVersion has @javax.persistence.Column", column);
      assertFalse("getVersion has @javax.persistence.Column(nullable=false)", column.nullable());

      Version version = getVersionMethod.getAnnotation(Version.class);
      assertNotNull("getVersion has @javax.persistence.Version", version);
    } catch (SecurityException e) {
      e.printStackTrace();
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    } catch (NoSuchMethodException e) {
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    }

    // setVersion
    try {
      Method setVersionMethod = _entityClass.getDeclaredMethod("setVersion", Integer.class);
      assertTrue(
          "private setVersion for " + _entityClass,
          Modifier.isPrivate(setVersionMethod.getModifiers()));
      assertFalse(
          "instance setVersion for " + _entityClass,
          Modifier.isStatic(setVersionMethod.getModifiers()));
      assertEquals(
          "setVersion return type for " + _entityClass,
          setVersionMethod.getReturnType(),
          void.class);
    } catch (SecurityException e) {
      e.printStackTrace();
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    } catch (NoSuchMethodException e) {
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    }
  }
예제 #28
0
파일: TUtils.java 프로젝트: imace/coffee
  // 获取插入记录的sql语句
  @SuppressWarnings("static-access")
  public static <T> String getInsertSql(T t, DialectType DialectType) throws Exception {
    String token = Configuration.getToken(DialectType);
    long start = System.currentTimeMillis();
    StringBuffer sql =
        new StringBuffer("insert into ").append(TUtils.getTableName(t.getClass())).append(" ");

    BeanInfo bi = Introspector.getBeanInfo(t.getClass(), Object.class);
    PropertyDescriptor[] props = bi.getPropertyDescriptors();
    // k-v 映射的column名字 : 属性  LinkedHashMap 按照插入的顺序排序
    Map<String, PropertyDescriptor> propMap = new LinkedHashMap<String, PropertyDescriptor>();
    sql.append("(");

    for (int i = 0; i < props.length; i++) {
      Field field = t.getClass().getDeclaredField(props[i].getName());
      Column column = field.getAnnotation(Column.class);
      Transient nullMap = field.getAnnotation(Transient.class);
      if (nullMap != null) {
        continue;
      }
      Id id = field.getAnnotation(Id.class);
      if (id != null) { // 主键
        if (Configuration.dialect == DialectType.HSQLDB) {
          continue;
        }
      }
      if (column != null) { // 数字 1 键旁边的反引号;处理关键字
        sql.append(token).append(column.name().toUpperCase()).append(token);
        propMap.put(column.name(), props[i]);
      } else {
        sql.append(token).append(props[i].getName().toUpperCase()).append(token);
        propMap.put(props[i].getName(), props[i]);
      }
      if (i + 1 < props.length) {
        sql.append(",");
      }
    }
    sql.append(")values(");
    for (String column : propMap.keySet()) {
      PropertyDescriptor prop = propMap.get(column);
      Object value = "";
      if (TUtils.isPrimaryKey(t.getClass(), prop)) {
        switch (DialectType) {
          case MYSQL:
            sql.append("null");
            break;
          case ORACLE:
            sql.append(TUtils.getSequenceName(t.getClass()) + ".nextval");
            break;
        }
      } else {
        switch (TypeUtils.getMappedType(prop)) {
          case Integer:
          case Long:
            sql.append(prop.getReadMethod().invoke(t, (Object[]) null));
            break;
          case Date:
            value = DateUtils.format(prop.getReadMethod().invoke(t, (Object[]) null));
            sql.append(null == value ? "null" : "'" + value.toString() + "'");
            //						sql.append(" to_date('").append(value).append("','yyyy-MM-dd HH24:mi:ss') ");
            break;
          case String:
            value = prop.getReadMethod().invoke(t, (Object[]) null);
            sql.append(null == value ? "null" : "'" + value.toString() + "'");
            break;
        }
      }
      sql.append(",");
    }
    sql.deleteCharAt(sql.length() - 1); // 除去sql语句后面最后一个 逗号
    sql.append(")");
    long end = System.currentTimeMillis();
    logger.info("生成sql耗时 " + (end - start) + " ms");
    logger.info(sql.toString());
    return sql.toString();
  }
예제 #29
0
파일: TUtils.java 프로젝트: imace/coffee
  /**
   * 获取插入记录的sql语句
   *
   * @param t : 实体
   */
  public static <T> String getInsertSql(T t) throws Exception {
    long start = System.currentTimeMillis();
    StringBuffer sql =
        new StringBuffer("insert into ").append(TUtils.getTableName(t.getClass())).append(" ");

    BeanInfo bi = Introspector.getBeanInfo(t.getClass(), Object.class);
    PropertyDescriptor[] props = bi.getPropertyDescriptors();
    // k-v 映射的column名字 : 属性  LinkedHashMap 按照插入的顺序排序
    Map<String, PropertyDescriptor> propMap = new LinkedHashMap<String, PropertyDescriptor>();
    sql.append("(");

    GenerationType generationType = null;
    String seqName = null;
    for (int i = 0; i < props.length; i++) {
      Field field = t.getClass().getDeclaredField(props[i].getName());
      Column column = field.getAnnotation(Column.class);
      Transient nullMap = field.getAnnotation(Transient.class);
      if (nullMap != null) {
        continue;
      }
      Id id = field.getAnnotation(Id.class);
      if (id != null) { // 主键
        // 如果是自增主键则不对其进行处理
        GeneratedValue gv = field.getAnnotation(GeneratedValue.class);
        if (gv == null) {
          throw new Exception("未指定主键生成策略");
        }
        generationType = gv.strategy();
        switch (generationType) {
          case IDENTITY:
            continue;
          case SEQUENCE:
            SequenceGenerator generator = field.getAnnotation(SequenceGenerator.class);
            seqName = generator.sequenceName();
            break;
        }
      }
      if (column != null) { // 数字 1 键旁边的反引号;处理关键字
        sql.append(column.name());
        propMap.put(column.name(), props[i]);
      } else {
        sql.append(props[i].getName());
        propMap.put(props[i].getName(), props[i]);
      }
      if (i + 1 < props.length) {
        sql.append(",");
      }
    }
    sql.append(")values(");
    for (String column : propMap.keySet()) {
      PropertyDescriptor prop = propMap.get(column);
      Object value = "";
      if (TUtils.isPrimaryKey(t.getClass(), prop)) {

        switch (generationType) {
          case AUTO:
            sql.append("null");
            break;
          case IDENTITY:
            break;
          case SEQUENCE:
            sql.append(seqName + ".nextval");
            break;
        }
      } else {
        switch (TUtils.getMappedType(prop.getPropertyType())) {
          case Integer:
          case Long:
            sql.append(prop.getReadMethod().invoke(t, (Object[]) null));
            break;
          case Date:
            value = TUtils.parseDate(prop.getReadMethod().invoke(t, (Object[]) null));
            if (Configuration.dialect == DialectType.ORACLE) {
              sql.append(" to_date('").append(value).append("','yyyy-MM-dd HH24:mi:ss') ");
            } else {
              sql.append(null == value ? "null" : "'" + value.toString() + "'");
            }
            break;
          case String:
            value = prop.getReadMethod().invoke(t, (Object[]) null);
            sql.append(null == value ? "null" : "'" + value.toString() + "'");
            break;
        }
      }
      sql.append(",");
    }
    sql.deleteCharAt(sql.length() - 1); // 除去sql语句后面最后一个 逗号
    sql.append(")");
    long end = System.currentTimeMillis();
    logger.info("生成sql耗时 " + (end - start) + " ms");
    logger.info(sql.toString());
    return sql.toString();
  }
예제 #30
0
 public static String getColumnName(PropertyDescriptor pd) {
   Column column = getAnnotation(pd, Column.class);
   return column.name();
 }