Skip to content

[功能改进]: 自定义字段名的映射规则 #6891

@SeraphinaLeo

Description

@SeraphinaLeo

确认

  • 我的版本是最新版本, 我的版本号与 version 相同, 并且项目里无依赖冲突
  • 我已经在 issue 中搜索过, 确认问题没有被提出过
  • 我已经修改标题, 将标题中的 描述 替换为你的想法(不得删除 描述 前面的部分)

功能改进

背景:在一般情况下,数据库中字段名通常使用下划线风格,在 Java 项目中使用小驼峰的风格,在默认情况下 Mybatis,Mybatis Plus 都可以很好的进行名称映射,但是数据库字段如果是其他的命名风格,就难以统一配置(比如严格的大驼峰字段名 -> Java的小驼峰命名),所以开启了探究 Mybatis + Mybatis Plus 是否可以联动配置统一字段名映射规则。

通过查阅资料,Mybatis 可以通过配置 ObjectWrapperFactoryObjectWrapper 来自定义 ResultSet 字段映射规则。
但是发现 Mybatis Plus 无法自定义字段名的映射规则,于是翻阅了源码。
mybatis-plus-core/com.baomidou.mybatisplus.core.metadata.TableFieldInfo 类中,在构造方法里对字段进行映射转化。
希望可以在未来版本中将字段映射改成可配置式的。

/**
 * 全新的 存在 TableField 注解时使用的构造函数
 */
public TableFieldInfo(GlobalConfig globalConfig, TableInfo tableInfo, Field field, TableField tableField, Reflector reflector, boolean existTableLogic) {    
	// ....
	String column = tableField.value();
	if (StringUtils.isBlank(column)) {
		column = this.property;
		if (tableInfo.isUnderCamel()) {
			/* 开启字段下划线申明 */
			column = StringUtils.camelToUnderline(column);
		}
		if (dbConfig.isCapitalMode()) {
			/* 开启字段全大写申明 */
			column = column.toUpperCase();
		}
		String columnFormat = dbConfig.getColumnFormat();
		if (StringUtils.isNotBlank(columnFormat)) {
			column = String.format(columnFormat, column);
		}
	} else {
		String columnFormat = dbConfig.getColumnFormat();
		if (StringUtils.isNotBlank(columnFormat) && tableField.keepGlobalFormat()) {
			column = String.format(columnFormat, column);
		}
	}
	this.column = column;
}

 /**
 * 不存在 TableField 注解时, 使用的构造函数
 */
public TableFieldInfo(GlobalConfig globalConfig, TableInfo tableInfo, Field field, Reflector reflector, boolean existTableLogic) {
	// ....
	String column = this.property;
	if (tableInfo.isUnderCamel()) {
		/* 开启字段下划线申明 */
		column = StringUtils.camelToUnderline(column);
	}
	if (dbConfig.isCapitalMode()) {
		/* 开启字段全大写申明 */
		column = column.toUpperCase();
	}

	String columnFormat = dbConfig.getColumnFormat();
	if (StringUtils.isNotBlank(columnFormat)) {
		column = String.format(columnFormat, column);
	}

	this.column = column;
}

-》

参考资料

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions