1.新建一个类继承 org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy这个类,它的表命名默认规则就是将驼峰式规则改为下划线相连,具体源码如下

	@Override
	public Identifier toPhysicalTableName(Identifier name,
			JdbcEnvironment jdbcEnvironment) {
		return apply(name, jdbcEnvironment);
	}

	private Identifier apply(Identifier name, JdbcEnvironment jdbcEnvironment) {
		if (name == null) {
			return null;
		}
		StringBuilder builder = new StringBuilder(name.getText().replace('.', '_'));
		for (int i = 1; i < builder.length() - 1; i++) {
			if (isUnderscoreRequired(builder.charAt(i - 1), builder.charAt(i),
					builder.charAt(i + 1))) {
				builder.insert(i++, '_');
			}
		}
		return getIdentifier(builder.toString(), name.isQuoted(), jdbcEnvironment);
	}

	protected Identifier getIdentifier(String name, boolean quoted,
			JdbcEnvironment jdbcEnvironment) {
		if (isCaseInsensitive(jdbcEnvironment)) {
			name = name.toLowerCase(Locale.ROOT);
		}
		return new Identifier(name, quoted);
	}

2.重写父类的 toPhysicalTableName() 方法来实现自定义表名规则(具体规则可以根据自己的业务需求来定),并将该类注册为Spring的bean,通过此方法也可以自定义字段的对应规则。

@Component
public class TableNameStrategy extends SpringPhysicalNamingStrategy {

    /**
     * 自定义表名转换
     *
     * @param name
     * @param jdbcEnvironment
     * @return
     */
    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        String tableName = name.getText();
        return Identifier.toIdentifier(tableName);
    }
}

3.关键的一步,在application.properties配置文件中指定表名生成规则的类为刚才写的类即可

spring.jpa.hibernate.naming.physical-strategy=com.annet.file.config.database.TableNameStrategy
01-14 15:09