Is it possible to dynamically define column names in Hibernate / JPA?

前端 未结 1 1153
感动是毒
感动是毒 2020-11-29 11:27

So i have this existing DB schema with a number of tables that i want to model with JPA/Hibernate. Each table has the same group of 30 additional columns ( to allow for runt

1条回答
  •  感动是毒
    2020-11-29 12:09

    You need to create a custom NamingStrategy.

    Assuming you use spring and hibernate with JPA, here is a configuration snippet with a custom NamingStrategy:

    
        
        
        
        
            
                
                
                
            
        
        
            
                
                    com.yourcompany.CustomNamingStrategy
                
            
        
    
    

    If you don't use spring, configuration will be different, but you can still use a custom NamingStrategy (see Implementing a NamingStrategy from the Hibernate Documentation).

    Anyway, here is a sample NamingStrategy that builds table names of the form TYPE1_TYPE2 for join tables and adds a common prefix to all tables:

    public class CustomNamingStrategy extends ImprovedNamingStrategy {
    
        private static final long serialVersionUID = 1L;
        private static final String PREFIX = "PFX_";
    
        @Override
        public String classToTableName(final String className) {
            return this.addPrefix(super.classToTableName(className));
        }
    
        @Override
        public String collectionTableName(final String ownerEntity,
                final String ownerEntityTable, final String associatedEntity,
                final String associatedEntityTable, final String propertyName) {
            return this.addPrefix(super.collectionTableName(ownerEntity,
                    ownerEntityTable, associatedEntity, associatedEntityTable,
                    propertyName));
        }
    
        @Override
        public String logicalCollectionTableName(final String tableName,
                final String ownerEntityTable, final String associatedEntityTable,
                final String propertyName) {
            return this.addPrefix(super.logicalCollectionTableName(tableName,
                    ownerEntityTable, associatedEntityTable, propertyName));
        }
    
        private String addPrefix(final String composedTableName) {
    
            return PREFIX
                    + composedTableName.toUpperCase().replace("_", "");
    
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题