简体   繁体   中英

Annotation shortcut (Hibernate's @Id, @GeneratedValue, @SequenceGenerator)

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 eq @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, eq ABC_MYCLASS_ID
  3. sequence, that generates ID column's values, has same name as ID column followed by _SEQ postfix, eq 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;

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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM