如何在Spring JPA R2DBC中使用CamelCase代替SnakeCase

问题描述 投票:0回答:1

我需要访问一个使用驼峰命名法作为表名和列名的旧数据库。

我希望指定精确匹配的 @Table 和 @Column 值能够起作用。但我指定的值也映射到snake_case。

有一些关于创建自定义 NamingStrategy 的参考。最深入的讨论位于 GitHub here。但该讨论暗示该问题已于 2021 年修复。

我正在使用最新的 spring boot (3.2.5),其中包括 spring-r2dbc (6.1.6),问题肯定没有得到解决。

spring-data-jpa spring-data-r2dbc
1个回答
0
投票

很多答案都在操纵 Hibernate 映射。当然R2DBC根本不使用hibernate。但实际答案仍然非常接近。

public class DataConfig  extends AbstractR2dbcConfiguration implements NamingStrategy {

// MUST define your ConnectionFactory here for whatever DB you're using
 public ConnectionFactory connectionFactory() {
...
}

public String getTableName(Class<?> type) {
    // Convert entity class name to table name as per your naming convention
    // For example, replace camelCase with underscores
    return toSnakeCase(type.getSimpleName());
}

@Override
public String getColumnName(RelationalPersistentProperty property) {
    // Convert property name to column name as per your naming convention
    // For example, replace camelCase with underscores
    return toSnakeCase(property.getName());
}

private String toSnakeCase(String camelCase) {
    return camelCase.replaceAll("(.)(\\p{Upper})", "$1$2").toLowerCase();
}

最重要的是toSnakeCase。您可以使用它来强制执行您想要的任何范例。就我而言,这就像将默认的“$1_$2”更改为“$1$2”一样简单。

© www.soinside.com 2019 - 2024. All rights reserved.