Search code examples
spring-dataspring-data-jdbc

How to tweak NamingStrategy for Spring Data JDBC


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 thomas.lang@th-deg.de
 */
@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;
    }

}

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

My existing Database has a column named campusname

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

Solution:

/**
     * 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(), "");
            }
        };
    }

Solution

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

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