本文介绍了如何调整 Spring Data JDBC 的 NamingStrategy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何调整 Spring Data JDBC NamingStrategy 使其表现得像 Hibernate 的 PhysicalNamingStrategy?
我有以下实体:

how do i tweak the Spring Data JDBC NamingStrategy to behave like Hibernate´s PhysicalNamingStrategy?
I have the following entity:

/**
 * Campus domain model class.
 * Handles information about campus.
 *
 * @author [email protected]
 */
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE, onConstructor = @__(@PersistenceConstructor))
public class Campus {

    private final @Id
    @Wither
    long campusId;

    @NotNull
    @Size(min = 3)
    private String campusName;

    /**
     * Creates a new campus.
     *
     * @param campusName
     */
    public Campus(@NonNull String campusName) {
        this.campusId = 0;
        Assert.hasLength(campusName, "A valid value has to be provided for Campus!");
        this.campusName = campusName;
    }

}

当我希望 JDBC 持久化测试记录时,它会生成此 sql:
[插入校园(campus_name)值(?)]

When i want JDBC to persist a test record, it generates this sql:
[INSERT INTO campus (campus_name) VALUES (?)]

我现有的数据库有一列名为 campusname

My existing Database has a column named campusname

我已经阅读了这里的文档https://docs.spring.io/spring-data/jdbc/docs/1.0.2.RELEASE/reference/html/#jdbc.entity-persistence.naming-strategy 我可以调整命名策略,但我不知道如何:)

I have read on the docu here https://docs.spring.io/spring-data/jdbc/docs/1.0.2.RELEASE/reference/html/#jdbc.entity-persistence.naming-strategy that i can tweak the naming strategy, but i don´t know how :)

感谢您的帮助!亲切的问候!托马斯

Thank you for your help!Kind regards!Thomas

解决方案:

/**
     * Naming strategy for naming entity columns
     * @see <a href="https://stackoverflow.com/questions/53334685/how-to-tweak-namingstrategy-for-spring-data-jdbc/53335830#53335830">How to implement {@link NamingStrategy}</a>
     *
     * @return PhysicalNamingStrategy
     */
    @Bean
    public NamingStrategy namingStrategy() {
        return new NamingStrategy() {
            @Override
            public String getColumnName(RelationalPersistentProperty property) {
                Assert.notNull(property, "Property must not be null.");
                return ParsingUtils.reconcatenateCamelCase(property.getName(), "");
            }
        };
    }

推荐答案

在您的应用程序上下文中创建一个 NamingStrategy 类型的 bean,并根据您的喜好实现其方法.

Create a bean of type NamingStrategy in your application context and implement its methods to your liking.

需要覆盖的方法是getColumnName(RelationalPersistentProperty)

The method that you need to override is getColumnName(RelationalPersistentProperty)

这篇关于如何调整 Spring Data JDBC 的 NamingStrategy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 13:39