Learning Spring-Data-Jpa (four) --- Naming naming strategy, source tracking

1, in the first entity Entity, naming two ways; 
one is the display name, i.e., designated by the database table name corresponding to the name attribute @Table, @ Column name attribute specifies the entity corresponding to the field name of the database field.
Another implicit name, the display name is generally not necessary, so that the name may not be provided, on the framework to make implicit name.

2, Naming naming strategy
we can find automatic configuration class org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration by spring-boot-autoconfigure the spring.factories.

    

    

 

 

    The automatic configuration class implementation class HibernateJpaConfiguration JpaBaseConfiguration introduced to perform the relevant hibernate jpa disposed; 
    

   when JpaBaseConfiguration entityManagerFactory configuration, called getVendorProperties method
to obtain the vendor property,
    
The method is implemented by HibernateJpaConfiguration, which is called the determineHibernateProperties HibernateProperties method, in accordance with standard settings and Hibernate JPA properties, determine the configuration of the main properties of the EntityManagerFactory Hibernate initialization.
    
继续往下走到Naming的applyNamingStrategies应用命名策略可以知道,如果我们不配置命名策略的话,默认由SpringImplicitNamingStrategy和SpringPhysicalNamingStrategy分两个阶段共同完成命名,
先走SpringImplicitNamingStrategy再走SpringPhysicalNamingStrategy。
    

     

 

  命名策略分两步走:

    第一步:如果我们没有使用@Table或@Column指定了表或字段的名称,则由SpringImplicitNamingStrategy为我们隐式处理,表名隐式处理为类名,列名隐式处理为字段名。如果指定了表名列名,SpringImplicitNamingStrategy不起作用。
第二步:将上面处理过的逻辑名称解析成物理名称。无论在实体中是否显示指定表名列名,SpringPhysicalNamingStrategy都会被调用。

所以如果我们想要自定义命名策略,可以根据自己的需求选择继承二者,并在配置文件中通过spring.jpa.hibernate.naming.implicit-strategy 或 spring.jpa.hibernate.naming.physical-strategy 进行指定自己的策略(例如为表名添加指定前缀)。
/**
 * 自定义命名策略
 *
 * @author caofanqi
 */
public class MySpringPhysicalNamingStrategy extends SpringPhysicalNamingStrategy {


    /**
     * 为表添加指定前缀
     */
    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        return super.toPhysicalTableName(new Identifier("cfq_" + name.getText(),name.isQuoted()), jdbcEnvironment);
    }


}
 

  

 

 

源码示例地址:https://github.com/caofanqi/study-spring-data-jpa
 

Guess you like

Origin www.cnblogs.com/caofanqi/p/11809535.html