ythy / blog

Give everything a shot
7 stars 0 forks source link

Spring Boot Naming Strategies #184

Open ythy opened 5 years ago

ythy commented 5 years ago

reference In hibernate 5, two new strategy was introduced to provide deep customization of the naming strategy and they are ImplicitNamingStrategy and PhysicalNamingStrategy. To use this strategy there are two keys to be used implicit_naming_strategy and physical_naming_strategy. Hibernate 5 provides only one implementation of PhysicalNamingStrategy - PhysicalNamingStrategyStandardImpl but several implementations of ImplicitNamingStrategy.

ImplicitNamingStrategy

When an entity does not explicitly name the database table that it maps to, we need to implicitly determine that table name. Or when a particular attribute does not explicitly name the database column that it maps to, we need to implicitly determine that column name

PhysicalNamingStrategy

Many organizations define rules around the naming of database objects (tables, columns, foreign-keys, etc). The idea of a PhysicalNamingStrategy is to help implement such naming rules without having to hard-code them into the mapping via explicit names.

While the purpose of an ImplicitNamingStrategy is to determine that an attribute named accountNumber maps to a logical column name of accountNumber when not explicitly specified, the purpose of a PhysicalNamingStrategy would be, for example, to say that the physical column name should instead be abbreviated acct_num.

It is true that the resolution to acct_num could have been handled in an ImplicitNamingStrategy in this case. But the point is separation of concerns. The PhysicalNamingStrategy will be applied regardless of whether the attribute explicitly specified the column name or whether we determined that implicitly. The ImplicitNamingStrategy would only be applied if an explicit name was not given. So it depends on needs and intent .

The default implementation is to simply use the logical name as the physical name. However applications and integrations can define custom implementations of this PhysicalNamingStrategy contract.

ythy commented 5 years ago

Spring Boot, provides defaults for both:

We can override these values, but by default, these will:

  1. Replace dots with underscores
  2. Change camel case to snake case, and
  3. Lower-case table names

So, for example, an AddressBook entity would be created as the address_book table.