Hibernate Learning (iii) Hibernate set prefix and delimiter for tables and fields

Source: Internet
Author: User
Tags modify table name tostring stringbuffer

In a mouthful of eating hibernate (i)--using the Schemaexport to generate a datasheet describes how to generate a data table. But that's just the basics. Hibernate has some limitations when it comes to generating or manipulating databases. For example, when you start designing a table, you write it directly into the user (Id,name,password,createtime) format. But the customer later asked the table name to start with "T_", the field name to "Stu_" start, can be some database keywords, words between "_" separated to facilitate their maintenance. For example: T_user (stu_id,stu_name,stu_create_time).

The general approach to the above problem is to modify the table in Hibernate_cfg.xml, add "t_" to each table, or write the table property, and the field also uses the column property to modify it. If you have 100 tables, each with an average of 10 fields, do you want to change one? It is possible to omit or correct the mistake. The most "hateful" thing is, if the customer again let you change to other, is not still want to change all?

Is there a way to do this without modifying the original configuration, adding and configuring table and field prefixes and delimiters, etc.?? After trying, I finally won, and now take out to share with you.

To solve the above problem, I mainly use the Namingstrategy interface. This interface is interesting and can be used as a bridge between the business class specification and the database table specification, and it can transform and process the mapping relationship of the table and column. For example, a data object USER, the corresponding database table is T_user, if all mapping relationship is such a case, you can use Namingstrategy as a bridge interface, without hbm.xml mapping file to specify the physical table corresponding to the class.

Let's talk about hibernate. The brief process of reading a mapping file: Looping through the class label to determine whether the class label's Table property value is null or NULL, The Classtotablename method of the Namingstrategy interface is invoked to convert the class value and process the name of the table (processed by the named Policy Namingstrategy). If it is not NULL, then the table is set, and the TableName method that calls the Namingstrategy interface gets the processed name. Loop through the property to determine if the column attribute value is NULL, or NULL, the Propertytocolumnname method is called first, the property value is converted to the column name, and the Logicalcolumnname method is called. If not NULL, the Logicalcolumnname method of the Namingstrategy interface is called directly, and the ColumnName method is invoked to process it (by the named Policy Namingstrategy).

Understanding the above mentioned process, as long as we implement namingstrategy this interface, you can modify the table map. Don't say more, directly on the code:

"Mynamingstrategy", a custom named policy that can be used to treat tables and fields uniformly.

Package Com.tgb.hibernate.neatlyDB;  
Import org.hibernate.cfg.Configuration;  
Import Org.hibernate.cfg.NamingStrategy;  
      
Import Org.hibernate.util.StringHelper;   
      
    /** * Database naming policy, customizable table, field, etc. prefix * * * @author Longxuan */public class Mynamingstrategy implements Namingstrategy {  
      
    /** * Database naming policy Single instance */private static mynamingstrategy instance = NULL;  
      
    /** * Database configuration information class * * private static databaseconfiguration dbcfg = null; /** * Privatization construction Method/Private Mynamingstrategy () {}/** * uses the simple mode to get the only real database naming policy Example * * @return/public static synchronized Mynamingstrategy getinstance () {//default read Hiber  
        Nate.cfg.xml file Configuration cfg = new Configuration (). Configure ();  
    return getinstance (CFG);        /** * uses simple mode to obtain a unique instance of the database naming policy, while using the default Hibernate.cfg.xml to update the named policy information * @param CFG *    Profile Information * @return */public static synchronized Mynamingstrategy getinstance (Configuration cfg) {  
        if (instance = = null) {instance = new Mynamingstrategy ();  
        } mynamingstrategy.dbcfg = new databaseconfiguration (CFG);  
    return instance; /** * uses simple mode to obtain a unique instance of the database naming policy while updating the named policy information * @param CFG * profile information * @return *url:http://www.bianceng.cn/programming/java/201410/45829.htm * * public static synchronized Mynamingst Rategy getinstance (databaseconfiguration dbcfg) {if (instance = null) {instance  
        = new Mynamingstrategy ();  
        } mynamingstrategy.dbcfg = Dbcfg;  
    return instance; /** * Set or update database configuration information * * @param dbcfg/public void Setdbconfig (Databaseconfigu  
    Ration dbcfg) {mynamingstrategy.dbcfg = dbcfg; 
   }  
      
    /**  * Convert to Physical table name * * @param the class value of the corresponding table in ClassName hbm.xml * * @Override public String Classtotablenam  
              
        E (String className) {if (className = null) return null;  
                  
        Change Case String str =updatestyle (Classname,dbcfg.gettablestyle (). name ());  
              
        Add prefix str = addprefixorstuffix (str, Dbcfg.gettableprefix (), Dbcfg.gettablesuffix ());  
              
        Add delimiter str = addseparator (Str,dbcfg.gettableseparator ());  
    return str; @Override public string Collectiontablename (string ownerentity, String ownerentitytable,  
    String associatedentity, String associatedentitytable, String propertyname) {return null; /** * Passes the Read column name to the processing, becomes the field name of the physical table * * @param columnName Logicalcolumnname Method Read to the column name */@Override public String columnName (String columnName) {///Call the Logicalcolumnname method first, get the processed value,//and then pass it to the method, so you can modify either of the two methods.  
              
        return columnName;  
              
        if (columnName = null) return null;  
                  
        Change Case String str =updatestyle (Columnname,dbcfg.getcolumntyle (). name ());  
              
        Add prefix str = addprefixorstuffix (stringhelper.unqualify (str), Dbcfg.getcolumnprefix (), Dbcfg.getcolumnsuffix ());  
              
        Add delimiter str = addseparator (Str,dbcfg.getcolumnseparator ());  
              
    return str;  /** * Process foreign key Column name */@Override public string Foreignkeycolumnname (string PropertyName, String Propertyentityname, String propertytablename, String Referencedcolumnnam  
              
        e) {if (referencedcolumnname = null) return null; Change Case String str =updatestyLe (Referencedcolumnname,dbcfg.getcolumntyle (). name ());  
              
        Add prefix str = addprefixorstuffix (stringhelper.unqualify (str), Dbcfg.getcolumnprefix (), Dbcfg.getcolumnsuffix ());  
              
        Add delimiter str = addseparator (Str,dbcfg.getcolumnseparator ());  
    return str; /** * The name of the association key */@Override public string Joinkeycolumnname (string joinedcolumn, String J  
              
        oinedtable) {if (Joinedcolumn = null) return null;  
                  
        Change Case String str =updatestyle (Joinedcolumn,dbcfg.getcolumntyle (). name ());  
              
        Add prefix str = addprefixorstuffix (stringhelper.unqualify (str), Dbcfg.getcolumnprefix (), Dbcfg.getcolumnsuffix ());  
              
        Add delimiter str = addseparator (Str,dbcfg.getcolumnseparator ());  
    return str; @Override Public String LogicalcollecTioncolumnname (String columnName, String propertyname, String referencedcolumn) {return null; @Override public string Logicalcollectiontablename (string tablename, String Ownerenti  
    Tytable, String associatedentitytable, String propertyname) {return null;    /** * Processing Logical column name * <b> if the column property is set, the call to the method </b> * * @param is invoked directly ColumnName  Column name * @param propertyname Entity Column name */@Override public string Logicalcolumnname (string columnName, String PropertyName) {//name value corresponds to Propertyname,column value columnname//judge whether the ColumnName is set, if set, then return C Olumn value, otherwise returns propertyname value return columnName = = NULL | | ColumnName = ""?  
              
    Propertyname:columnname; /** * Processing Logical column name * <b> if the column property is not set, call the method first, and then call the Logicalcolumnname method </b> * *
 @param propertyname Entity Column Name * *   @Override public String Propertytocolumnname (String propertyname) {if (PropertyName = null) Retu  
              
        RN null;  
                  
        Change Case String str =updatestyle (Propertyname,dbcfg.getcolumntyle (). name ());  
              
        Add prefix str = addprefixorstuffix (stringhelper.unqualify (str), Dbcfg.getcolumnprefix (), Dbcfg.getcolumnsuffix ());  
              
        Add delimiter str = addseparator (Str,dbcfg.getcolumnseparator ());  
    return str; /** * Process Table name * <b> If you set a table property, this method is invoked </b>/@Override Publi  
              
        C String TableName (string tablename) {if (TableName = null) return null;  
                  
        Change Case String str =updatestyle (Tablename,dbcfg.gettablestyle (). name ()); Add prefix str = addprefixorstuffix (stringhelper.unqualify (str), Dbcfg.gettableprefix (), Dbcfg.gettablesUffix ());  
              
        Add delimiter str = addseparator (Str,dbcfg.gettableseparator ());  
    return str; /** * Word delimiter * * @param name * @return/private String AddSeparator (Str ing str, String flag) {StringBuffer buf = new StringBuffer (str.substring (Str.lastindexof (".")  
        +1)); for (int i = 1; i < Buf.length ()-1; i++) {if (' _ '!= Buf.charat (i-1) &&amp ; Character.isuppercase (Buf.charat (i)) &&!  
                Character.isuppercase (Buf.charat (i + 1))) {//Buf.insert (i++, ' _ ');  
            Buf.insert (i++, flag);  
    } return buf.tostring ();            /** * Add prefix * * @param str * String * @param prefix * Prefix * @param suffix * suffix * @return/private String ADDPREfixorstuffix (String str, string prefix, string suffix) {stringbuffer buf = new StringBuffer (str. LastIndexOf (".")  
        +1));  
        Buf.insert (Buf.length (), suffix). Insert (0, prefix);  
    return buf.tostring (); /** * Update style * @param str * @param style * @return */Private String Update  
        Style (String str, string style) {if ("AU". Equals (Style)) {str = str.touppercase ();  
        else if ("AL". Equals (Style)) {str = str.tolowercase (); else if ("FU". Equals (Style)) {StringBuffer buf = new StringBuffer (str.substring (Str.lastindexof (".")  
            +1));  
            String Upper =buf.substring (0,1). toUpperCase ();  
            Buf.delete (0, 1). Insert (0, Upper);  
        str = buf.tostring (); else if ("FL". Equals (Style)) {StringBuffer buf = new StringBuffer (str.substring (Str.lastindexof (".")  
            +1)); String LoWer =buf.substring (0,1). toLowerCase ();  
            Buf.delete (0, 1). Insert (0, lower);  
        str = buf.tostring ();  
    } else{} return str; }  
          
          
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.