Hibernate命名策略

hibernate的命名策略,可以减少对数据库标识符命名的维护,进一步减少这部份命名的重复性代码量,以提高维护。

hibernate的命名方式,有两类,一类是显式命名,一类是隐式命名。

  • 显式命名:在映射配置时,设置的数据库表名,列名等,就是进行显式命名。
  • 隐式命名:显式命名一般不是必要的,所以可以选择当不设置名称,这时就交由hibernate进行隐式命名,另外隐式命名还包括那些不能进行显式命名的数据库标识符。接口ImplicitNamingStrategy,就是用于实现隐式命名。
  • 过滤命名:接口PhysicalNamingStrategy,用于对显式命名或隐式命名进一步过滤处理。

示例:

TestTable1Impl.java

@Entity
// 隐式命名表名
@Table
public class TestTable1Impl {
    //---------------------------------------------------------------
    // Field
    //---------------------------------------------------------------

    @Id
    @Column()
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long testId;

    @Column(length = 20)
    private String testName;

    @ManyToOne
    private TestTable2Impl testForeign;

    //---------------------------------------------------------------
    // Method
    //---------------------------------------------------------------

    public Long getId() {
        return testId;
    }

    public void setId(Long id) {
        this.testId = id;
    }

    public String getName(){
        return testName;
    }

    public void setName(String name){
        this.testName = name;
    }

    public TestTable2Impl getTestForeign() {
        return testForeign;
    }

    public void setTestForeign(TestTable2Impl testForeign) {
        this.testForeign = testForeign;
    }
}

TestTable2Impl.java

@Entity
// 显式命名表名
@Table(name = "TestTable2Impl")
public class TestTable2Impl {
    //---------------------------------------------------------------
    // Field
    //---------------------------------------------------------------

    @Id
    @Column()
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long testId;

    @Column(length = 20)
    private String testName;

    //---------------------------------------------------------------
    // Method
    //---------------------------------------------------------------

    public Long getId() {
        return testId;
    }

    public void setId(Long id) {
        this.testId = id;
    }

    public String getName(){
        return testName;
    }

    public void setName(String name){
        this.testName = name;
    }
}

MyImplicitNamingStrategyImpl.java

public class MyImplicitNamingStrategyImpl extends ImplicitNamingStrategyJpaCompliantImpl implements ImplicitNamingStrategy {

    @Override
    public Identifier determinePrimaryTableName(ImplicitEntityNameSource source) {
        Identifier name = super.determinePrimaryTableName(source);
        Identifier result = toStandard(name, "Impl");
        System.out.println("ImplicitNamingStrategy / PrimaryTableName -> \n\t" + name + " => " + result);
        return result;
    }

    private Identifier toStandard(Identifier name, String... removeSuffixes){
        if(removeSuffixes == null)
            return name;

        if(name == null)
            return null;

        String text = name.getText();
        if(removeSuffixes != null){
            for(String suffix : removeSuffixes){
                if(text.endsWith(suffix))
                    text = text.substring(0, text.length() - suffix.length());
            }
        }
        return new Identifier(text, name.isQuoted());
    }

    @Override
    public Identifier determineJoinTableName(ImplicitJoinTableNameSource source) {
        Identifier name = super.determineJoinTableName(source);
        System.out.println("ImplicitNamingStrategy / JoinTableName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineCollectionTableName(ImplicitCollectionTableNameSource source) {
        Identifier name = super.determineCollectionTableName(source);
        System.out.println("ImplicitNamingStrategy / CollectionTableName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineDiscriminatorColumnName(ImplicitDiscriminatorColumnNameSource source) {
        Identifier name = super.determineDiscriminatorColumnName(source);
        System.out.println("ImplicitNamingStrategy / DiscriminatorColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineTenantIdColumnName(ImplicitTenantIdColumnNameSource source) {
        Identifier name = super.determineTenantIdColumnName(source);
        System.out.println("ImplicitNamingStrategy / TenantIdColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineIdentifierColumnName(ImplicitIdentifierColumnNameSource source) {
        Identifier name = super.determineIdentifierColumnName(source);
        System.out.println("ImplicitNamingStrategy / IdentifierColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineBasicColumnName(ImplicitBasicColumnNameSource source) {
        Identifier name = super.determineBasicColumnName(source);
        System.out.println("ImplicitNamingStrategy / BasicColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineJoinColumnName(ImplicitJoinColumnNameSource source) {
        Identifier name = super.determineJoinColumnName(source);
        final String result;

        if ( source.getNature() == ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION || source.getAttributePath() == null ) {
            result = transformEntityName( source.getEntityNaming() );
        } else {
            result = transformAttributePath( source.getAttributePath() );
        }

        System.out.println("ImplicitNamingStrategy / JoinColumnName -> \n\t" + name + " => " + result);
        return toIdentifier( result, source.getBuildingContext() );
    }

    @Override
    public Identifier determinePrimaryKeyJoinColumnName(ImplicitPrimaryKeyJoinColumnNameSource source) {
        Identifier name = super.determinePrimaryKeyJoinColumnName(source);
        System.out.println("ImplicitNamingStrategy / PrimaryKeyJoinColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineAnyDiscriminatorColumnName(ImplicitAnyDiscriminatorColumnNameSource source) {
        Identifier name = super.determineAnyDiscriminatorColumnName(source);
        System.out.println("ImplicitNamingStrategy / AnyDiscriminatorColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineAnyKeyColumnName(ImplicitAnyKeyColumnNameSource source) {
        Identifier name = super.determineAnyKeyColumnName(source);
        System.out.println("ImplicitNamingStrategy / AnyKeyColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineMapKeyColumnName(ImplicitMapKeyColumnNameSource source) {
        Identifier name = super.determineMapKeyColumnName(source);
        System.out.println("ImplicitNamingStrategy / MapKeyColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineListIndexColumnName(ImplicitIndexColumnNameSource source) {
        Identifier name = super.determineListIndexColumnName(source);
        System.out.println("ImplicitNamingStrategy / ListIndexColumnName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineForeignKeyName(ImplicitForeignKeyNameSource source) {
        Identifier name = super.determineForeignKeyName(source);
        String result = null;
        String tableName = source.getTableName().getText();
        if(tableName.startsWith(TableNamingConfig.TABLE_PREFIX))
            tableName = tableName.substring(TableNamingConfig.TABLE_PREFIX.length());
        if(source.getColumnNames().size() == 1){
            result = TableNamingConfig.FOREIGN_KEY_PREFIX + tableName + "_" + source.getColumnNames().get(0).getText();
        } else  {
            String columnName = source.getReferencedTableName().getText();
            if(columnName.startsWith(TableNamingConfig.TABLE_PREFIX))
                columnName = columnName.substring(TableNamingConfig.TABLE_PREFIX.length());
            result = TableNamingConfig.FOREIGN_KEY_PREFIX + tableName + "_" + columnName;
        }
        System.out.println("ImplicitNamingStrategy / ForeignKeyName -> \n\t" + name + " => " + result);
        return new Identifier(result, name.isQuoted());
    }

    @Override
    public Identifier determineUniqueKeyName(ImplicitUniqueKeyNameSource source) {
        Identifier name = super.determineUniqueKeyName(source);
        System.out.println("ImplicitNamingStrategy / UniqueKeyName -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier determineIndexName(ImplicitIndexNameSource source) {
        Identifier name = super.determineIndexName(source);
        System.out.println("ImplicitNamingStrategy / IndexName -> \n\t" + name);
        return name;
    }

}

MyPhysicalNamingStrategyImpl.java

public class MyPhysicalNamingStrategyImpl implements PhysicalNamingStrategy {

    @Override
    public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        System.out.println("PhysicalNamingStrategy / catalog -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        System.out.println("PhysicalNamingStrategy / schema -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        Identifier result = toStandard(name, "tb_");
        System.out.println("PhysicalNamingStrategy / table -> \n\t" + name + " => " + result);
        return result;
    }

    @Override
    public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        System.out.println("PhysicalNamingStrategy / sequence -> \n\t" + name);
        return name;
    }

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) {
        Identifier result = toStandard(name);
        System.out.println("PhysicalNamingStrategy / column -> \n\t" + name + " => " + result);
        return result;
    }

    private Identifier toStandard(Identifier name){
        return toStandard(name, null);
    }

    private Identifier toStandard(Identifier name, String prefix){
        if(name == null)
            return null;

        String text = name.getText();
        StringBuffer buffer = new StringBuffer();
        if(prefix != null)
            buffer.append(prefix);

        char[] chars = text.toCharArray();
        for(int i=0, len=chars.length; i<len; i++){
            char c1 = chars[i];
            if(c1 >= ‘A‘ && c1 <= ‘Z‘){
                if(i > 0 && i + 1 < len){
                    if(chars[i + 1] < ‘A‘ || chars[i + 1] > ‘Z‘)
                        buffer.append(‘_‘);
                }
                c1 = (char) (c1 - ‘A‘ + ‘a‘);
            }
            buffer.append(c1);
        }
        return new Identifier(buffer.toString(), name.isQuoted());
    }

}

TableNamingConfig.java

public class TableNamingConfig {
    public static final String TABLE_PREFIX = "tb_";
    public static final String FOREIGN_KEY_PREFIX = "fk_";
}

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <bean id="physicalNamingStrategy" class="test.MyPhysicalNamingStrategyImpl"></bean>
    <bean id="implicitNamingStrategy" class="test.MyImplicitNamingStrategyImpl"></bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <!-- 可以加多个包 -->
                <value>test</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
            </props>
        </property>
        <property name="physicalNamingStrategy" ref="physicalNamingStrategy"></property>
        <property name="implicitNamingStrategy" ref="implicitNamingStrategy"></property>
    </bean>
</beans>

Test.java

public class Test {
    public static void main(String[] params){
        // 命名策略
        new Test().test();
        /*
            PhysicalNamingStrategy / catalog ->
                null
            PhysicalNamingStrategy / catalog ->
                null
            PhysicalNamingStrategy / column ->
                DTYPE => dtype
            ImplicitNamingStrategy / PrimaryTableName ->
                TestTable1Impl => TestTable1
            PhysicalNamingStrategy / table ->
                TestTable1 => tb_test_table1
            ImplicitNamingStrategy / BasicColumnName ->
                testId
            PhysicalNamingStrategy / column ->
                testId => test_id
            ImplicitNamingStrategy / BasicColumnName ->
                testId
            ImplicitNamingStrategy / BasicColumnName ->
                testForeign
            PhysicalNamingStrategy / column ->
                testForeign => test_foreign
            ImplicitNamingStrategy / BasicColumnName ->
                testName
            PhysicalNamingStrategy / column ->
                testName => test_name
            ImplicitNamingStrategy / BasicColumnName ->
                testName
            PhysicalNamingStrategy / column ->
                DTYPE => dtype
            PhysicalNamingStrategy / table ->
                TestTable2Impl => tb_test_table2_impl
            ImplicitNamingStrategy / BasicColumnName ->
                testId
            PhysicalNamingStrategy / column ->
                testId => test_id
            ImplicitNamingStrategy / BasicColumnName ->
                testId
            ImplicitNamingStrategy / BasicColumnName ->
                testName
            PhysicalNamingStrategy / column ->
                testName => test_name
            ImplicitNamingStrategy / BasicColumnName ->
                testName
            ImplicitNamingStrategy / JoinColumnName ->
                testForeign_testId => testForeign
            PhysicalNamingStrategy / column ->
                testForeign => test_foreign
            ImplicitNamingStrategy / ForeignKeyName ->
                FKlnurug7wfle1u6fc5oulnrx94 => fk_test_table1_test_foreign

            Hibernate:
                alter table tb_test_table1
                   drop
                   foreign key fk_test_table1_test_foreign

            Hibernate:
                drop table if exists tb_test_table1

            Hibernate:
                drop table if exists tb_test_table2_impl

            Hibernate:
                create table tb_test_table1 (
                   test_id bigint not null auto_increment,
                    test_name varchar(20),
                    test_foreign bigint,
                    primary key (test_id)
                )

            Hibernate:
                create table tb_test_table2_impl (
                   test_id bigint not null auto_increment,
                    test_name varchar(20),
                    primary key (test_id)
                )

            Hibernate:
                alter table tb_test_table1
                   add constraint fk_test_table1_test_foreign
                   foreign key (test_foreign)
                   references tb_test_table2_impl (test_id)

            Hibernate:
                alter table tb_test_table1
                   drop
                   foreign key fk_test_table1_test_foreign

            Hibernate:
                drop table if exists tb_test_table1

            Hibernate:
                drop table if exists tb_test_table2_impl
         */
    }

    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml", this.getClass());
        SessionFactory factory = null;
        try {
            factory = (SessionFactory) context.getBean("sessionFactory");
        } finally {
            if(factory != null){
                factory.close();
                factory = null;
            }
        }
    }
}
时间: 2024-10-25 05:54:01

Hibernate命名策略的相关文章

攻城狮在路上(壹) Hibernate(三)--- 属性访问、命名策略、派生属性、指定包名等

一.hibernate访问持久化类属性的策略: 在<property>元素中的access属性用于指定Hibernate访问持久化类属性的方式. 常见的方式如下: 1.property:默认值.hibernate通过相应的getXXX()和setXXX()方法. 2.field:hibernate运用反射机制直接访问类的属性. 3.自定义方式:自己写一个实现org.hibernate.property.PropertyAccessor接口的类,在access属性中写类的全限定名. 举例: ?

hibernate创建命名策略

1.hibernate提供命名接口NamingStrategy.同时提供两种参考的命名策略.DefaultNamingStaregy 和ImporvedNamingStartegy 覆盖对应的方法就可以了. 2.如何在定义数据库表的时候,没有定义table ,则调用,定义了就按定义的命名策略. 3.类的属性同上. 4.让配置策略起左右.  new Configuration .setNamingStrategy(new MyNamingStrategy()) ;

Hibernate修改命名策略

> 两步: 第一步:写一个替代Hibernate默认命名规则类(本类目标是把java[骆驼命名] 转换成 [下划线命名]) package paltform.init; import org.hibernate.cfg.ImprovedNamingStrategy; import org.hibernate.cfg.NamingStrategy; /**  * HIBERNATE 数据库字段命名规则  * */ public class HibernateNamingStrategy exten

spring boot 中Spring data jpa数据库表字段命名策略

spring boot 中Spring data jpa命名策略 数据库,表字段命名是驼峰命名法(UserID),Spring data jpa 自动更新之后是 user_id, 表字段不对照, Spring data jpa基于Hibernate5.0 application.properties 写法 1.无修改命名 spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNa

Hibernate检索策略之延迟加载和立即加载

延迟加载:延迟加载(lazy load懒加载)是当在真正需要数据时,才执行SQL语句进行查询.避免了无谓的性能开销. 延迟加载分类:  1.类级别的查询策略 2.一对多和多对多关联的查询策略 3.多对一关联的查询策略 什么情况下使用延迟加载? 如果程序加载一个对象的目的是为了访问它的属性,可以采用立即加载.如果程序加载一个持久化对象的目的是仅仅为了获得它的引用,可以采用延迟加载. 如何配置延时加载? 在Hibernate中通过对.hbm的lazy属性来赋值,不同位置出现lazy的作用和取值也是不

Hibernate —— 检索策略

一.Hibernate 的检索策略本质上是为了优化 Hibernate 性能. 二.Hibernate 检索策略包括类级别的检索策略.和关联级别的检索策略(<set> 元素) 三.类级别的检索策略 1. 立即检索.延迟检索 2. 通过 <class> 节点的 lazy 属性来控制.默认为 true,即为延迟检索. 3. 只针对 session 的 load() 方法生效. 默认情况下,通过 load() 方法获取到的对象是一个代理对象,Hibernate 创建代理对象时,仅会初始化

三大框架 之 Hibernate生成策略与缓存策略(主键生成策略、持久化、持久化类划分、一级缓存、事物管理)

目录 Hibernate生成策略与缓存策略 主键生成策略 主键分类 主键的生成策略 持久化 什么是持久化 什么是持久化类 持久化类编写规则 持久化类的划分 三种状态区分 持久态对象特征 一级缓存 什么是缓存 一级缓存 一级缓存特点 一级缓存内部结构 事务管理 什么是事务 事务特性 事务的隔离级别 Hibernate设置事务的隔离级别 事务业务层连接 Hibernate生成策略与缓存策略 主键生成策略 主键分类 自然主键 主键本身就是表中的一个字段 实体中一个具体的属性,对象本身唯一的特性 创建一

hibernate(八) Hibernate检索策略(类级别,关联级别,批量检索)详解

序言 很多看起来很难的东西其实并不难,关键是看自己是否花费了时间和精力去看,如果一个东西你能看得懂,同样的,别人也能看得懂,体现不出和别人的差距,所以当你觉得自己看了很多书或者学了很多东西的时候,你要想想,你花费的也就那么一点时间,别人花你这么多时间也能够学到你所学到的东西,所以还是要继续努力.既然不是天才,唯有靠勤奋来弥补. --WH 一.概述 检索策略分三大块,类级别检索策略和关联级别检测策略. 类级别检索策略:get.load. 关联级别检索策略:order.getCustomer().g

Hibernate 检索策略

概述 检索数据时的 2 个问题: –不浪费内存:当 Hibernate 从数据库中加载 Customer 对象时, 如果同时加载所有关联的 Order 对象, 而程序实际上仅仅需要访问 Customer 对象, 那么这些关联的 Order 对象就白白浪费了许多内存. –更高的查询效率:发送尽可能少的 SQL 语句 类级别的检索策略 •类级别可选的检索策略包括立即检索和延迟检索, 默认为延迟检索 –立即检索: 立即加载检索方法指定的对象 –延迟检索: 延迟加载检索方法指定的对象.在使用具体的属性时