• Home
  • Mastering the Name Game: JPA Naming Conventions in Spring Boot
  • Entity Class Names: Remain unchanged (e.g., User, Product).
  • Table Names: Derived from the entity class name by converting camel case to snake case and converting all letters to lowercase (e.g., user, product).
  • Column Names: Derived from the entity’s field names using the same snake case conversion (e.g., first_name, price).
  • Database Compatibility: Some databases enforce stricter naming rules or have limitations on character casing. Custom conventions can ensure compatibility.
  • Improved Readability: For complex entity relationships or adherence to a specific database naming standard, custom conventions can enhance readability.
  • Legacy System Integration: When integrating with existing databases that have established naming conventions, customization can simplify the process.

Setting Up Custom Naming Conventions

  1. Implement a NamingStrategy Bean:Create a bean that implements the javax.persistence.EntityNamingStrategy interface. This interface defines methods for customizing table and column names.
  2. Override Naming Logic:Within the bean, override the getName() method for tables and the propertyToColumnName() method for columns. Implement your desired naming logic within these methods.
  3. Configure EntityManagerFactory:In your Spring Boot application configuration, use @EnableJpaRepositories and specify the custom NamingStrategy bean using the nameStrategy property: @EnableJpaRepositories(nameStrategy = MyCustomNamingStrategy.class) public class MyApplication { // … }
public class UpperSnakeCaseNamingStrategy implements EntityNamingStrategy {

    @Override
    public String getName(EntityInfo<?> entity) {
        return entity.getEntityName().replaceFirst("^([A-Z])", "_$1")
                .toUpperCase().replace('.', '_');
    }

    @Override
    public String propertyToColumnName(SingularAttribute<?, ?> property) {
        return null; // Use default conversion for columns (optional)
    }
}

Leave Comment