Naming policy when entity mappings are in hibernate

Source: Internet
Author: User
Tags table name mysql database


Sometimes when an entity class is mapped to a database table, we do not pay much attention to the names of the tables and columns that are generated, either by using the default name policy or simply by using the field names without @column annotations, or by using the name attribute in the @column annotation. But sometimes, for example, to design a database with a unified prefix or suffix, the above two methods are not applicable, but need a unified design naming strategy, this article summarizes this part. 1, the historical version of the naming strategy Namingstrategy

In the older version of Hibernate, if you want to specify a naming policy that applies to the global, then it is necessary to involve the Namingstrategy interface, which is implemented directly or indirectly by all classes that want to customize the naming policy. The inheritance structure of this interface is as follows:

We generally do not directly implement the Namingstrategy interface, because we will implement all the interface methods, sometimes this is not necessary, so we generally directly inherit the Namingstrategy implementation class, such as Defaultnamingstrategy, This is the default naming policy for hibernate, or Improvednamingstrategy uses _ to separate the fields and choose which class to inherit primarily by looking at our own needs. Here we use Hibernate's default naming policy Defaultnamingstrategy to inherit.
Let's start by explaining that the three classes that will be used are the same as those used in the previous article, namely the person, address, and direction classes.

Person class

@Entity public
class person implements serializable{
private static final long Serialversionuid = 8849870114127659929L;

    @Id
    @GeneratedValue
    private Long Id;

    @Column (nullable = False)
    private String name;

    @Column (nullable = False)
    private Integer age;

    @Embedded
    @AttributeOverrides ({@AttributeOverride (name= "Direction.latitude", column= @Column (name = "Person_ Latitude ")),
       @AttributeOverride (name=" direction.longitude ", column = @Column (name =" Person_longitude ")})
    private address address;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Address class:

@Embeddable public
class Address implements serializable{
    private static final long Serialversionuid = 8849870114128959929L;

    @Column (nullable = False)
    private String country;
    @Column (length =)
    private String province;
    @Column (unique = true)
    private String city;
    @Column (length =)
    private String detail;

    @Embedded
    private Direction Direction;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Direction class:

@Embeddable public
class Direction implements serializable{

    @Column (nullable = False)
    Private Integer longitude;
    Private Integer latitude;
}
1 2 3 4 5 6 7

Next we customize the naming strategy, which uses the Apache common dependency package, as follows:

public class Entitynamingstrategy extends Defaultnamingstrategy {
    @Override public
    String Propertytocolumnname (String propertyname) {
        string column = Propertyname.replaceall ("\ \", "_");
        Return "C_" + column;
    }

    @Override public
    string Classtotablename (String className) {
        return "T_" + stringutils.capitalize (className);
    }

    @Override public
    string TableName (String tableName) {
        return super.tablename (tableName);
    }

    @Override public
    string ColumnName (String columnName) {
        return super.columnname (columnName);
    }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

Here we first look at these 4 methods, basically these 4 are the most common: Propertytocolumnname: This is used to use the field property name or field property path expression as a parameter to map the corresponding column name, the key point is to use the path expression , this is when you use a reference type field, such as a field of a custom type, to map with a path expression, as if the address Type field is used in the person class above, which is the argument passed into the method Address.country, Address.city, etc. classtotablename: This method is easier to understand, is to pass in the corresponding class of the fully qualified class name , not just a common class name, and then through this parameter to determine the mapping table name; TableName: It is based on the table name defined in the mapping document to modify the mapping strategy, because we basically use annotations to map, so this method is not used; ColumnName: It is based on the column names defined in the mapping document to modify the mapping strategy, since we basically use annotations to map, So this way is not often used;

Defining the mapping strategy above, how do we make this custom class work? This is much easier if we use spring boot to build our program. You only need to configure Spring.jpa.hibernate.naming-strategy for our custom naming policy in configuration file Application.properties com.springboot.demo.mapping.EntityNaming Strategy can be;

In addition, if you are using just plain web engineering, there are two ways to make our naming policy work: programmatically, as follows: Through the Hibernate.cfg.xml file configuration: The specific configuration to open the following related articles of the first article, because the specific configuration is cumbersome, but also not often used, here will not repeat;

Configuration cfg = new configuration (). Configure ();
Cfg.setnamingstrategy (New Entitynamingstrategy ());
Standardserviceregistrybuilder SRB = new Standardserviceregistrybuilder (). Applysettings (Cfg.getproperties ());
standardserviceregistry sr = Srb.build ();
Sessionfactory factory = Cfg.buildsessionfactory (SR);
1 2 3) 4 5

To understand the above and related configurations, let's look at the results of the specific build:

We will specifically analyze the content and related issues: First look at the generated table name, feel with US set the wrong ah, our settings are T_ class name, but the generation is really t_ class name all lowercase, in fact, the table name generation is not only related to our program, but also related to the corresponding database and operating system , because we are using a MySQL database, in its configuration file My.ini has lower_case_table_names used to control the case of the table name, as shown in Workbench:
The base Type field in person is mapped to the C_ field name, which is generated according to our logic, the base type field in the reference type address in person is mapped to the C_ field name, and the field name is delimited by "_"; The reference type fields in the reference type address in person are mapped to Person_latitude, Person_longitude, and not generated according to our custom build strategy, which indicates a problem The global naming policy we defined was overwritten by the @attributeoverrides annotations, which means that our global policy doesn't work with this annotation, so let's take a look at the table structure below to delete this annotation:

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.