Java Code Examples for javax.persistence.Column#name()

The following examples show how to use javax.persistence.Column#name() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MybatisPersistentPropertyImpl.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public String getColumnName() {

	if (isAnnotationPresent(Column.class)) {
		Column column = getRequiredAnnotation(Column.class);
		if (StringUtils.hasText(column.name())) {
			return column.name();
		}
	}

	if (isAnnotationPresent(OrderColumn.class)) {
		OrderColumn orderColumn = getRequiredAnnotation(OrderColumn.class);
		if (StringUtils.hasText(orderColumn.name())) {
			return orderColumn.name();
		}
	}

	return getOwner().getFieldNamingStrategy().getFieldName(this);
}
 
Example 2
Source File: HqlGenerateUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 根据字段名称返回hibernate映射数据库字段名
 * @param clazz
 * @param field_name	字段名称
 * @return
 */
public static String invokeFindColumn(Class clazz,String field_name){
	String column=null;
	Field field;
	try {

		//TODO	只能向上找一级,其他则失败。
		boolean flag = getSuperDeclaredField(clazz,field_name);
		if(flag) {
			field = clazz.getDeclaredField(field_name);
		} else {
			Class cla = clazz.getSuperclass();
			field = cla.getDeclaredField(field_name);
		}

		PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);  
        Method getMethod = pd.getReadMethod();//获得get方法 
		Column col=getMethod.getAnnotation(Column.class);
		if(col!=null){
			column=col.name();
		}
	} catch (Exception e) {
		return column;
	}
	return column;
}
 
Example 3
Source File: SqlGenerateUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 获取属性对应的数据库列名
 * @param propertyDescriptor
 * @return
 */
public static String getDbNameByFieldName(PropertyDescriptor propertyDescriptor){
	String propertyName = propertyDescriptor.getName();
	Column column = null;
	Method readMethod = propertyDescriptor.getReadMethod();
	if(readMethod!=null){
		column = readMethod.getAnnotation(Column.class);
		if(column==null){
			Method writeMethod = propertyDescriptor.getWriteMethod();
			if(writeMethod!=null){
				column = writeMethod.getAnnotation(Column.class);
			}
		}
	}
	
	//如果找不到@column,或者@column的name为空,那么数据库列名就是属性名
	if(column==null || StringUtil.isEmpty(column.name())){
		return propertyName;
	}else{
		return column.name();
	}
}
 
Example 4
Source File: ResultSetRecordConverter.java    From java-tool with Apache License 2.0 6 votes vote down vote up
private Object convertToEntity(Object entity) throws SQLException {
    List<Field> fields = classMetaInfoRepo.get(targetType);
    if (null == fields) {
        fields = $.fieldsOf(targetType);
        classMetaInfoRepo.put(targetType, fields);
    }
    Map<String, Integer> columnNameLookup = columnNameLookup();
    for (Field f : fields) {
        Column column = f.getAnnotation(Column.class);
        String label = null != column ? column.name() : f.getName();
        if (null != reverseSpecialMaps) {
            String newLabel = reverseSpecialMaps.get(label);
            if (null != newLabel) {
                label = newLabel;
            }
        }
        Integer n = columnNameLookup.get(label);
        if (null == n) {
            continue;
        }
        Class fieldType = f.getType();
        Object o = getFieldValue(n);
        $.setFieldValue(entity, f, $.convert(o).to(fieldType));
    }
    return entity;
}
 
Example 5
Source File: EntityHelper.java    From mybatis-dynamic-query with Apache License 2.0 5 votes vote down vote up
static String getColumnNameByProperty(final String propertyName, final Field[] properties) {
    Field matchProperty = getPropertyField(propertyName, properties);
    Column column = getColumnByProperty(propertyName, properties);
    if (column != null && StringUtils.isNotBlank(column.name())) {
        return column.name();
    }


    String usePropertyName = matchProperty.getName();
    return camelCaseToUnderscore(usePropertyName);
}
 
Example 6
Source File: EntityUtils.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private static String getPropertyName(final Field field) {
    final Column columnAnnotation = field.getAnnotation(Column.class);
    if (columnAnnotation != null && !columnAnnotation.name().isEmpty()) {
        return columnAnnotation.name();
    } else {
        return field.getName();
    }
}
 
Example 7
Source File: EntityManager.java    From dal with Apache License 2.0 5 votes vote down vote up
private void processAllFields(String currentClassName, Field[] allFields, Map<String, String> columnNamesMap,
							  Set<String> classNameSet) throws SQLException {

	for (Field field : allFields) {
		Column column = field.getAnnotation(Column.class);
		Id id = field.getAnnotation(Id.class);
		if (column == null && id == null)
			continue;

		if (field.getAnnotation(Type.class) == null)
			throw new DalException(ErrorCode.TypeNotDefined);

		String columnName =
				(column == null || column.name().trim().length() == 0) ? field.getName() : column.name();

		String tempClassName = columnNamesMap.get(columnName);
		if (tempClassName != null) {
			if (tempClassName.equals(currentClassName)) {
				throw new DalException(ErrorCode.DuplicateColumnName); // If two fields with same column name are in
				// same class,then we throw an exception.
			} else {
				continue; // If two fields with same column name are distributed in different class,then we abandom
				// current field.
			}
		}

		columnNamesMap.put(columnName, currentClassName);

		processField(columnName, field);

		processUpdatableColumn(columnName, column);
		processInsertableColumn(columnName, column);

		processPrimaryKeyColumn(id, columnName);
		processAutoIncrementColumn(field, currentClassName, classNameSet);

		processSensitiveColumn(columnName, field);
		processVersionColumn(columnName, field, currentClassName, columnNamesMap);
	}
}
 
Example 8
Source File: MetaClassRepresentation.java    From cuba with Apache License 2.0 5 votes vote down vote up
public String getColumnName() {
    Column column = property.getAnnotatedElement().getAnnotation(Column.class);
    if (column != null)
        return column.name();

    JoinColumn joinColumn = property.getAnnotatedElement().getAnnotation(JoinColumn.class);
    return joinColumn != null ? joinColumn.name() : "";
}
 
Example 9
Source File: AccessibleProperty.java    From warpdb with Apache License 2.0 5 votes vote down vote up
private static String getColumnName(AccessibleObject ao, String defaultName) {
	Column col = ao.getAnnotation(Column.class);
	if (col == null || col.name().isEmpty()) {
		return defaultName;
	}
	return col.name();
}
 
Example 10
Source File: JPAEdmProperty.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
private String getReferenceColumnName(AnnotatedElement annotatedElement2, Attribute<?, ?> referencedAttribute) {
  String refColName = null;
  Column c = annotatedElement2.getAnnotation(Column.class);
  if(c != null) {
    refColName = c.name();
  }
  return refColName == null || "".equals(refColName)
      ? referencedAttribute.getName()
      : refColName;
}
 
Example 11
Source File: ModelSqlUtils.java    From jdbctemplatetool with Apache License 2.0 5 votes vote down vote up
/**
 * use getter to guess column name, if there is annotation then use annotation value, if not then guess from field name
 * @param getter
 * @param f
 * @return
 * @throws NoColumnAnnotationFoundException
 */
private static String getColumnNameFromGetter(Method getter,Field f){
	String columnName = "";
	Column columnAnno = getter.getAnnotation(Column.class);
	if(columnAnno != null){
		//如果是列注解就读取name属性
		columnName = columnAnno.name();
	}
	
	if(columnName == null || "".equals(columnName)){
		//如果没有列注解就用命名方式去猜
		columnName = IdUtils.toUnderscore(f.getName());
	}
	return columnName;
}
 
Example 12
Source File: BaseSQLProvider.java    From QuickProject with Apache License 2.0 5 votes vote down vote up
private String parseIdColumn() {
    String idColumn = "ID";
    try {
        Method getIdMethod = modelClass.getMethod("getId", null);
        Column idColumnAnnotation = getIdMethod.getAnnotation(Column.class);
        if (idColumnAnnotation != null && idColumnAnnotation.name() != null) {
            idColumn = idColumnAnnotation.name();
        }
    } catch (NoSuchMethodException e) {
        log.error(e.getMessage(), e);
    }
    return idColumn;
}
 
Example 13
Source File: PersistentUtil.java    From mybatis-jpa with Apache License 2.0 5 votes vote down vote up
public static String getColumnName(Field field, NamingStrategy namingStrategy) {
  if (field.isAnnotationPresent(Column.class)) {
    Column column = field.getAnnotation(Column.class);
    if (!"".equals(column.name().trim())) {
      return column.name();
    }
  }
  String columnName = field.getName();

  return namingStrategy.translate(columnName);
}
 
Example 14
Source File: FieldMapper.java    From mybatis.flying with Apache License 2.0 5 votes vote down vote up
public static String getColumnName(Column column, Field field) {
	if (!"".equals(column.name())) {
		return column.name();
	} else {
		return field.getName();
	}
}
 
Example 15
Source File: HibernateQueryFactory.java    From elepy with Apache License 2.0 5 votes vote down vote up
private String getJPAFieldName(Field field) {
    Column annotation = com.elepy.utils.Annotations.get(field,Column.class);

    if (annotation != null && !annotation.name().isEmpty()) {
        return annotation.name();
    }

    return field.getName();
}
 
Example 16
Source File: EntityHelper.java    From azeroth with Apache License 2.0 4 votes vote down vote up
/**
 * 由传入的实体的class构建TableMapper对象,构建好的对象存入缓存中,以后使用时直接从缓存中获取
 *
 * @param entityClass
 * @return TableMapper
 */
public static EntityMapper getEntityMapper(Class<?> entityClass) {

    synchronized (entityClass) {
        // 先从map中获取实体映射信息
        EntityMapper entityMapper = tableMapperCache.get(entityClass);

        // 如果存在直接返回
        if (entityMapper != null) {
            return entityMapper;
        }

        TableMapper tableMapper = getTableMapper(entityClass);

        //获取实体ID泛型
        Class<?> idClass = getIdClass(entityClass);

        // 获取实体字段列表
        List<Field> fields = getAllField(entityClass);
        // 全部列
        Set<ColumnMapper> columnMapperSet = new HashSet<ColumnMapper>();
        // 主键
        ColumnMapper idColumn = null;
        GenerationType idStrategy = null;

        for (Field field : fields) {

            // 排除字段
            if (field.isAnnotationPresent(Transient.class)) {
                continue;
            }
            ColumnMapper columnMapper = new ColumnMapper();

            // 数据库字段名
            String columnName = null;
            if (field.isAnnotationPresent(Column.class)) {
                Column column = field.getAnnotation(Column.class);
                columnName = column.name();
                columnMapper.setInsertable(column.insertable());
                columnMapper.setUpdatable(column.updatable());
            }
            // 如果为空,使用属性名并替换为下划线风格
            if (columnName == null || columnName.equals("")) {
                columnName = camelhumpToUnderline(field.getName());
            }

            columnMapper.setProperty(field.getName());
            columnMapper.setColumn(columnName);
            columnMapper.setJavaType(field.getType());

            // 是否主键
            if (field.isAnnotationPresent(Id.class)) {
                columnMapper.setId(true);
                if (field.isAnnotationPresent(GeneratedValue.class)) {
                    idStrategy = field.getAnnotation(GeneratedValue.class).strategy();
                }
                idColumn = columnMapper;
            }
            // 添加到所有字段映射信息
            columnMapperSet.add(columnMapper);

        }
        if (columnMapperSet.size() <= 0) {
            throw new RuntimeException("实体" + entityClass.getName() + "不存在映射字段");
        }
        if (idColumn == null) {
            throw new RuntimeException("实体" + entityClass.getName() + "不存在主键或者");
        }

        // 解析实体映射信息
        entityMapper = new EntityMapper();
        entityMapper.setTableMapper(tableMapper);
        entityMapper.setColumnsMapper(columnMapperSet);
        entityMapper.setIdClass(idClass);
        entityMapper.setIdColumn(idColumn);
        entityMapper.setIdStrategy(idStrategy);

        tableMapperCache.put(entityClass, entityMapper);

        return entityMapper;
    }
}
 
Example 17
Source File: EntityHelper.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
/**
 * 由传入的实体的class构建TableMapper对象,构建好的对象存入缓存中,以后使用时直接从缓存中获取
 * 
 * @param entityClass
 * @return TableMapper
 */
public static EntityMapper getEntityMapper(Class<?> entityClass) {

    synchronized (entityClass) {
        // 先从map中获取实体映射信息
        EntityMapper entityMapper = tableMapperCache.get(entityClass);

        // 如果存在直接返回
        if (entityMapper != null) {
            return entityMapper;
        }

        TableMapper tableMapper = getTableMapper(entityClass);

        //获取实体ID泛型
        Class<?> idClass = getIdClass(entityClass);

        // 获取实体字段列表
        List<Field> fields = getAllField(entityClass);
        // 全部列
        Set<ColumnMapper> columnMapperSet = new HashSet<ColumnMapper>();
        // 主键
        ColumnMapper idColumn = null;
        GenerationType idStrategy = null;

        for (Field field : fields) {

            // 排除字段
            if (field.isAnnotationPresent(Transient.class)) {
                continue;
            }
            ColumnMapper columnMapper = new ColumnMapper();

            // 数据库字段名
            String columnName = null;
            if (field.isAnnotationPresent(Column.class)) {
                Column column = field.getAnnotation(Column.class);
                columnName = column.name();
                columnMapper.setInsertable(column.insertable());
                columnMapper.setUpdatable(column.updatable());
            }
            // 如果为空,使用属性名并替换为下划线风格
            if (columnName == null || columnName.equals("")) {
                columnName = camelhumpToUnderline(field.getName());
            }

            columnMapper.setProperty(field.getName());
            columnMapper.setColumn(columnName);
            columnMapper.setJavaType(field.getType());

            // 是否主键
            if(field.isAnnotationPresent(Id.class)){                	
            	columnMapper.setId(true);
            	if(field.isAnnotationPresent(GeneratedValue.class)){ 
            		idStrategy = field.getAnnotation(GeneratedValue.class).strategy();
            	}
            	idColumn = columnMapper;
            }
            // 添加到所有字段映射信息
            columnMapperSet.add(columnMapper);
            //
            field.setAccessible(true);
            entityFieldMappings.put(field.getName(), field);
        }
        if (columnMapperSet.size() <= 0) {
            throw new RuntimeException("实体" + entityClass.getName() + "不存在映射字段");
        }
        if (idColumn == null) {
            throw new RuntimeException("实体" + entityClass.getName() + "不存在主键");
        }

        // 解析实体映射信息
        entityMapper = new EntityMapper();
        entityMapper.setTableMapper(tableMapper);
        entityMapper.setColumnsMapper(columnMapperSet);
        entityMapper.setIdClass(idClass);
        entityMapper.setIdColumn(idColumn);
        entityMapper.setIdStrategy(idStrategy);

        tableMapperCache.put(entityClass, entityMapper);

        return entityMapper;
    }
}
 
Example 18
Source File: EntityMetaManager.java    From das with Apache License 2.0 4 votes vote down vote up
public static EntityMeta extract(Class<?> clazz) {
    if(registeredTable.containsKey(clazz)) {
        return registeredTable.get(clazz);
    }
    
    String tableName = null;
    TableDefinition td = null;
    Map<String, ColumnDefinition> colMap = new HashMap<>();
    try {
        Field tableDef = clazz.getDeclaredField(clazz.getSimpleName().toUpperCase());
        td = (TableDefinition)tableDef.get(null);
        tableName = td.getName();
    } catch (Throwable e) {
        // It is OK for only the query entity
    }
    if(td != null) {
        for(ColumnDefinition colDef: td.allColumns()) {
            colMap.put(colDef.getColumnName(), colDef);
        }
    }
    
    Field[] allFields = clazz.getDeclaredFields();
    if (null == allFields || allFields.length == 0) {
        throw new IllegalArgumentException("The entity[" + clazz.getName() +"] has no fields.");
    }

    Map<String, Field> fieldMap = new HashMap<>();
    Field idField = null;
    List<ColumnMeta> columns = new ArrayList<>();
    for (Field f: allFields) {
        Column column = f.getAnnotation(Column.class);
        Id id =  f.getAnnotation(Id.class);

        // Column must be specified
        if (column == null) {
            continue;
        }

        String columnName = column.name().trim().length() == 0 ? f.getName() : column.name();
        if(tableName != null) {
            Objects.requireNonNull(colMap.get(columnName), "Column " + columnName + " must be defined in " + tableName);
        }
        
        f.setAccessible(true);
        fieldMap.put(columnName, f);
        
        GeneratedValue generatedValue = f.getAnnotation(GeneratedValue.class);
        boolean autoIncremental = null != generatedValue && 
                (generatedValue.strategy() == GenerationType.AUTO || generatedValue.strategy() == GenerationType.IDENTITY);
        
        if(idField != null && autoIncremental) {
            throw new IllegalArgumentException("Found duplicate Id columns");
        } else if (id != null) {
            idField = f;
        }
        
        JDBCType type = colMap.containsKey(columnName) ? colMap.get(columnName).getType() : null;
        columns.add(new ColumnMeta(
                columnName,
                type,
                autoIncremental,
                id != null,
                column.insertable(),
                column.updatable(),
                f.getAnnotation(Version.class) != null));
    }

    if(tableName!= null && columns.size() != colMap.size()) {
        throw new IllegalArgumentException("The columns defined in table definition does not match the columns defined in class");
    }
    
    EntityMeta tableMeta = new EntityMeta(td, columns.toArray(new ColumnMeta[0]), fieldMap, idField);
    
    registeredTable.putIfAbsent(clazz, tableMeta);
    
    return registeredTable.get(clazz);
}