欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Hibernate命名策略详解

程序员文章站 2024-03-08 14:36:04
hibernate的命名策略,可以减少对数据库标识符命名的维护,进一步减少这部份命名的重复性代码量,以提高维护。 hibernate的命名方式,有两类,一类是显式命名,一...

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

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

1)显式命名:在映射配置时,设置的数据库表名,列名等,就是进行显式命名。

2)隐式命名:显式命名一般不是必要的,所以可以选择当不设置名称,这时就交由hibernate进行隐式命名,另外隐式命名还包括那些不能进行显式命名的数据库标识符。接口implicitnamingstrategy,就是用于实现隐式命名。

3)过滤命名:接口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;
      }
    }
  }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!

上一篇: spring MVC搭建及配置详解

下一篇: