示例#1
0
 /** 获得实体类中每个非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();
 }
  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);
    }
  }
示例#3
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;
      }
    }
  }
示例#4
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;
  }
  /*
   * ************************************************************************
   * 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);
  }
示例#6
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();
           }
         }
       }
     }
   }
 }
示例#7
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();
    }
  }
示例#8
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;
   }
 }
 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;
 }
示例#10
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;
 }
 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;
 }
示例#12
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;
 }
示例#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 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()]);
 }
示例#16
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();
    }
  }
示例#17
0
 public static String getColumnName(PropertyDescriptor pd) {
   Column column = getAnnotation(pd, Column.class);
   return column.name();
 }
示例#18
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();
  }
示例#19
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();
  }