0

Code simplification needed. In our company we have patterns on how to create names for DB objects (see list below), these applies to all classes/tables, which results in tons of repeated code in every Entity class (see code example). I was able to simplify table name generation with custom naming strategy. But, using naming strategy, ID column is generated only from its property name, but I need also a Class/Table name as part of it. Same applies to valueGenerator.

Is there any option how to apply theese rules only with custom NamingStrategy? I can also imagine solution using custom annotation e.q. @AcmeId, that takes project prefix from configuration and "expands itself" to these four annotations, if this is possible (can you please point me to some example?).

Patterns

  1. table included in project have project name as prefix, so table for MyClass entity in project ABC has name ABC_MYCLASS)
  2. ID column name consists of table name followed by _ID, e.q. ABC_MYCLASS_ID
  3. sequence, that generates ID column's values, has same name as ID column followed by _SEQ postfix, e.q. ABC_MYCLASS_ID_SEQ
  public class MyClass {

   static final String CLASS_NAME = "MYCLASS";
   static final String TABLE_NAME = PROJECT_PREFIX + CLASS_NAME;
   static final String COLUMN_ID_NAME = PROJECT_PREFIX + CLASS_NAME + AcmeNamingStrategy.ID_COLUMN_POSTFIX;
   static final String SEQUENCE_NAME = PROJECT_PREFIX + CLASS_NAME + AcmeNamingStrategy.SEQUENCE_POSTFIX;

   @Id
   @Column(name = COLUMN_ID_NAME)
   @SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME)
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_NAME)
   private Long id;
Jan Zdrha
  • 373
  • 2
  • 11

1 Answers1

0

This approach will allow you to determine table and sequence names easily.

If you name the id properties consistently as id, it will also solve the id-naming problem:

public class CustomNamingStrategy extends DefaultNamingStrategy {

    ...
@Override
    public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        String result = super.toPhysicalColumnName(identifier, jdbcEnv);
        return "id".equals(identifier.getText()) ? "ABC_" + result : result;
    }

}
crizzis
  • 9,978
  • 2
  • 28
  • 47
  • Thank you for response. Tables are OK, but column's and sequence's names are not. For column name I need to use, as part of it, table/entity name in them, but I don't get this in method in your example. Iedntifier only provides me "property name" but not "entity name". – Jan Zdrha Apr 10 '21 at 09:00