Java programmer from Stupid Bird to rookie (55) Hibernate (vi) Hibernate inheritance relationship mapping __java

Source: Internet
Author: User



In the field of Object-oriented programming, a class is inherited from a class, such as a parent-child relationship in the Java world that requires only the extends keyword to determine the two classes, but in the world of relational databases, there are no keywords between tables and tables that explicitly indicate the parent-child relationship between the two tables. Tables and tables are not inherited from this argument. In order to reflect the inheritance relationship in the program realm to the data, Hibernate provides us with 3 solutions:


The first scenario: a subclass corresponds to a table.

The second scenario is to use a table to represent the set of properties for all classes under the inheritance system.

The third scenario: each subclass uses a table to store only its own properties, and then associates the table corresponding to the parent class with a one-to-one primary key.


These three programs are in the official language:

TPS: A table for each subclass (table per subclass).

TPH: Each class inherits the tree using a table (table per class hierarchy)

TPC: Class table inheritance. Each concrete Class A table (table per concrete Class) (some restrictions)

Now let's take a look at the pros and cons of each of the three options and get acquainted with the three scenarios. Now suppose there are people, Student, teacher three classes, the parent class is people,student and teacher is the parent class of people, the code is as follows:

People class:

public class people

{

    /* Parent Property

    /private stringid;

    Private Stringname;

    Private stringsex;

    Private stringage;

    Private Timestampbirthday;

    /*get and Set Method */

}

Student class:
Public class Student extends people

{/

    * Student unique attribute/

   private string cardid;//Learn number public

   string Getcardid ()

   {return cardid;}

   public void Setcardid (String cardid)

   {

        this.cardid = Cardid;

   }}

Teacher Class:
Public class Teacher extends people

{

   /*teacher unique attribute/

    privateint salary;//Payroll public

   INT Getsalary ()

    {return

       salary;

    }

   public void setsalary (int salary)

    {

       this.salary = salary;

    }

}


The first scenario: a subclass corresponding to a table (TPS)

The scheme is to make each subclass of the inheritance system correspond to a table in the database. The schematic diagram is as follows:


Each subclass corresponds to a database table that contains information about the parent class and contains its own unique attributes. Each subclass corresponds to a table, and the information for the table is complete, which contains all the fields from the attribute mappings inherited from the parent class. This strategy uses the <union-subclass> tag to define subclasses.

To configure the People.hbm.xml file:

<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">  

The above configuration is a subclass a table scheme configuration,<union-subclass> tag is a subclass of the class that indicates the hbm file, such as a people class with two subclasses, which requires two <union-subclass> labels and so on. The "name" property of the <union-subclass> label is used to specify the fully qualified name of the subclass, the table property is used to specify the name of the tables corresponding to the subclass, and the "extends" property is used to specify the parent class of the subclass, noting that the property and < Union-subclass> the position of the label, if the <union-subclass> label as a child of the <class> label, the "extends" property can not be set, or you need to explicitly set the "Extends" property. The "abstract" property in the <class> label if the value is true, the table structure is not generated. A value of false generates the table structure, but does not insert data.

Depending on the People.hbm.xml build table structure, you can see that a subclass corresponds to a table:

drop table if exists student

   drop table if exists teacher

    CREATE TABLE student (

        ID varchar (255) Not null,
  
   name varchar (255),

        sex varchar (255), Age

        varchar (255),

        birthday datetime,

        cardid varchar (255),

        primary KEY (ID)

    )

    CREATE TABLE teacher (

        ID varchar (255) NOT NULL,

        name varchar (255),

        sex varchar (255), Age

        varchar ( 255),

        birthday datetime,

        salary integer,

        primary key (ID)

    )
  


The second scenario: Use a table to represent the collection of attributes for classes under all inherited systems (TPH)

This strategy is implemented using the <subclass> tag. Because there are many subclasses in the class inheritance system, to keep information about multiple classes in a single table, there must be a mechanism for distinguishing which records belong to which class. The mechanism in Hibernate is to add a field to the table, using the value of the field to differentiate. Add this indicator column to the table to use the <discriminator> tag to implement it.

Schematic diagram of this strategy:

After all the class information in the inheritance system is represented in the same table, any attributes that are not in the class are automatically assigned null.

Configure People.hbm.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">  


The <discriminator> label is used to create an identity column in the table whose column property specifies the name of the identity column, and type specifies the identity column. The <subclass> label specifies that the HBM file represents a subclass of the class, how many subclasses have that label, and its Name property specifies the subclass, and the "Discriminator-value" property specifies what the value of the identity column of the data for the subclass is, and its " The extends property is consistent with the <union-subclass> extends property usage.

Here's a look. Based on the People.hbm.xml build table structure, you can see that a table contains all the information under the inheritance system, where "Peopletype" is the identity column:

Drop table if exists people

    createtable people (

        Idvarchar (255) NOT NULL,

       peopletype varchar (255) Not null,
  namevarchar (255),

        Sexvarchar (255),

        Agevarchar (255),

       birthday datetime,

        Cardidvarchar (255),

        Salaryvarchar (255),

       primary key (ID)

    )

The third scenario: Each subclass uses a table to store only its own properties, and then associates the table corresponding to the parent class with a one-to-one primary key. (TPC)

This strategy uses the <joined-subclass> tag to define subclasses. The parent class and subclass all correspond to a database table. In the database table corresponding to the parent class, it stores the public information for all records, and in fact the table for that parent class contains all the records, including the records of the parent class and subclasses, and in the database table for the subclass, the table defines only the fields of the attribute mappings that are unique to the subclass. The data table for the subclass corresponds to the data table of the parent class, and is associated by a one-to-one primary key association.

Schematic diagram of this strategy:


All records of subclasses are stored in the people table, but only the information they share is recorded. And their unique information is stored in their corresponding table, a record to obtain its unique information, through the people record's primary key to its corresponding child table to find the same record of the primary key value and then take out its unique information.

Configure People.hbm.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">  


<joined-subclass> tags need to include a key tag that specifies which field the subclass and parent are associated with.

According to the People.hbm.xml build table structure, you can see that the corresponding table of the parent class holds public information, the corresponding table of the subclass holds the unique information, and the table corresponding to the subclass and the parent class is associated with a one-to-one primary key association.

Drop table if exists people

   drop table if exists student

    droptable if exists teacher

   create table people (
  
   id varchar (255) NOT NULL,

        name varchar (255),

        sex varchar (255), Age

        varchar (255),

        birthday datetime,

        primary KEY (ID)

   )

   CREATE TABLE student (

        ID varchar (255) NOT NULL,

        cardid varchar (255),

        primary key (ID)

   )

   CREATE TABLE teacher (

        ID varchar (255) NOT NULL,

        salary integer,

        primary key (ID)

   )

 

   ALTER TABLE Student

        Add index FK8FFE823BF9D436B1 (ID),

        add constraint fk8ffe823bf9d436b1

        foreign key (ID)

        References people (ID)

 

   ALTER TABLE teacher

        Add index fkaa31cbe2f9d436b1 (ID),

        add constraint FKAA31CBE2F9D436B1

        foreign key (ID)

        references people (ID)


  


comparison and selection of three kinds of mapping methods and their advantages and disadvantages---three kinds of methods

In order to facilitate the description for three ways in order of the marking for [1][2][3].

"1": Advantages: Clear Data structure

Disadvantage: The primary key for two child tables cannot be duplicated, and the primary key cannot be generated using the database's self-amplification method.

"2": Advantages: High query efficiency, in line with database design coarse granularity (recommended)

Disadvantage: There are redundant fields, some of which are attributes that subclasses do not have.

"3": Advantages: Clear data structure, no redundancy

Disadvantages: The class of inheritance more than the same, resulting in the table is also a lot of changes, additions and deletions to check inefficient

Summarize:

1. By summarizing the advantages and disadvantages of these three approaches, it seems that using the inheritance tree to generate a table appears to be more in line with the principle of database coarse-grained design. Of course the amount of data is very large, you can also consider the way each class generates a table

2. The object model of the program has not changed, the change is the relational model.

This is the benefit of hibernate, want to change the relational model, only need to change the mapping file.

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.