Hibernate inheritance ing

Source: Internet
Author: User

Inheritance and polymorphism are two basic concepts for object-oriented programming languages. The inheritance ing of Hibernate can understand the inheritance relationship between persistence classes. For example, the relationship between people and students. If a student inherits a person, he or she can think of the student as a special person. If the student queries the person, the student instance will also be obtained.

Hibernate supports three inheritance and ing policies:

Use subclass for ing: map each entity object in the domain model to an independent table, that is, the inheritance and polymorphism in the domain model are not considered in the relational data model.
Use joined-subclass for ing: For subclasses in the inheritance relationship, use the same table. Therefore, you need to add additional fields to the database table to distinguish subclass types.
Use union-subclass for ing: each class in the domain model maps to a table and describes the inheritance relationships between tables through foreign keys in the relational data model. This is equivalent to creating tables in the database according to the structure of the domain model, and establishing the inheritance relationship between tables through foreign keys.


Using the subclass element inheritance ing using the subclass inheritance ing, you can use the same table for the parent class and subclass in the inheritance relationship.
Because the instances of the parent class and subclass are all stored in the same table, you need to add a column to the table, this column is used to identify the instance of the class to which each row is recorded. This column is called a discriminator ).
In this ing policy, subclass is used to map child classes. The discriminator-value Attribute of class or subclass is used to specify the values of the speaker column. All fields defined by the Child classes cannot have non-null constraints. If a non-null constraint is added for those fields, the instance of the parent class does not have a value in those columns. This will cause a database integrity conflict, and the instance of the parent class cannot be saved to the database.


Use the inheritance ing of joined-subclass Elements
When you use the inheritance ing of joined-subclass elements to implement this ing policy for a table of each subclass, the parent class instance is saved in the parent class table, subclass instances are jointly stored by parent and child tables. Because the subclass instance is also a special parent class instance, it must also contain the attributes of the parent class instance. Therefore, the attributes common to the Child class and the parent class are saved in the parent class table. The attributes added to the Child class are saved in the Child class table. In this ing policy, you do not need to use the authenticator column, but you need to use the key element for each subclass to map a common primary key. You can add non-null constraints to attributes added to subclass. Because the attributes of subclass and parent classes are not saved in the same table

Use the inheritance ing of the union-subclass Element
The union-subclass element can be used to map each object to an independent table.
The attributes added to the subclass can have non-null constraints-that is, the data of the parent class instance is stored in the parent table, and the data of the Child class instance is stored in the Child class table.
The data of the subclass instance is only stored in the subclass table, but there is no record in the parent table.
In this ing policy, the fields in the subclass table are more than those in the parent table, because the fields in the subclass table are equal to the fields in the parent table and the sum of attributes added to the subclass table, in this ing policy, the authenticator column is not required, you do not need to use the key element to map the common primary key. the union-subclass ing policy is not applicable to the primary key generation policy of identity, because the same primary key seed must be used for all object classes in the same class hierarchy, that is, the primary keys of records corresponding to multiple persistent entities should be continuous. this affects native primary key generation policies, because native selects identity or sequence based on the database.


Vcq9tcSxyL3PIDxicj4KCjxpbWcgc3JjPQ = "http://www.2cto.com/uploadfile/Collfiles/20140602/20140602090325204.png" alt = "\">


Use the inheritance ing of subclass Elements
Example Description: Person. java
package com.atguigu.hibernate.subclass;public class Person {private Integer id;private String name;private int age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

Student. java
package com.atguigu.hibernate.subclass;public class Student extends Person{private String school;public String getSchool() {return school;}public void setSchool(String school) {this.school = school;}}

Person. hbm. xml
 
     
          
               
                
            
                   
   
           
               
            
                   
               
            
                   
           
           
            
               
  
 

Package com. atguigu. hibernate. subclass; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. SQL. blob; import java. SQL. connection; import java. SQL. SQLException; import java. util. date; import java. util. list; import java. util. set; import org. hibernate. hibernate; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import org. hibernate. jdbc. work; import org. hibernate. service. serviceRegistry; import org. hibernate. service. serviceRegistryBuilder; import org. junit. after; import org. junit. before; import org. junit. test; public class HibernateTest {private SessionFactory sessionFactory; private Session session; private Transaction transaction; @ Beforepublic void init () {Configuration configuration Configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry); session = sessionFactory. openSession (); transaction = session. beginTransaction () ;}@ Afterpublic void destroy () {transaction. commit (); session. close (); sessionFactory. close ();}/*** disadvantages: * 1. use the discerning column. * 2. non-null constraints cannot be added for fields unique to subclass. * 3. if the hierarchy is deep, there will be more fields in the data table. * // *** query: * 1. to query a parent record, you only need to query one data table * 2. for subclass records, you only need to query a data table */@ Testpublic void testQuery () {List
 
  
Persons = session. createQuery ("FROM Person"). list (); System. out. println (persons. size (); List
  
   
Stus = session. createQuery ("FROM Student "). list (); System. out. println (stus. size ();}/*** insert operation: * 1. for subclass objects, you only need to insert records into a data table. * 2. the discerning column is automatically maintained by Hibernate. * // @ Testpublic void testSave () {Person person = new Person (); person. setAge (11); person. setName ("AA"); session. save (person); Student stu = new Student (); stu. setAge (22); stu. setName ("BB"); stu. setSchool ("ATGUIGU"); session. save (stu );}}
  
 


Use the inheritance ing of joined-subclass Elements
Example Description: Person. java
package com.atguigu.hibernate.joined.subclass;public class Person {private Integer id;private String name;private int age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

Student. java
package com.atguigu.hibernate.joined.subclass;public class Student extends Person{private String school;public String getSchool() {return school;}public void setSchool(String school) {this.school = school;}}

Person. hbm. xml
 
     
          
               
                
            
                   
               
            
                   
               
            
                   
           
            
            
               
  
 

Package com. atguigu. hibernate. joined. subclass; import java. util. list; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; import org. hibernate. service. serviceRegistryBuilder; import org. junit. after; import org. junit. before; import org. junit. test; public class HibernateTest {private SessionFactory sessionFactory; private Session session; private Transaction transaction; @ Beforepublic void init () {Configuration configuration Configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry); session = sessionFactory. openSession (); transaction = session. beginTransaction () ;}@ Afterpublic void destroy () {transaction. commit (); session. close (); sessionFactory. close ();}/*** advantages: * 1. the user column does not need to be used. * 2. non-null constraints can be added for fields unique to subclass. * 3. no redundant fields. * // *** query: * 1. query the parent record and perform a left outer join query * 2. for subclass records, perform an inner join query. * // @ Testpublic void testQuery () {List
 
  
Persons = session. createQuery ("FROM Person"). list (); System. out. println (persons. size (); List
  
   
Stus = session. createQuery ("FROM Student "). list (); System. out. println (stus. size ();}/*** insert operation: * 1. A subclass object must be inserted into at least two data tables. * // @ Testpublic void testSave () {Person person = new Person (); person. setAge (11); person. setName ("AA"); session. save (person); Student stu = new Student (); stu. setAge (22); stu. setName ("BB"); stu. setSchool ("ATGUIGU"); session. save (stu );}}
  
 


Use the inheritance ing of the union-subclass Element
Person. java
package com.atguigu.hibernate.union.subclass;public class Person {private Integer id;private String name;private int age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

Student. java
package com.atguigu.hibernate.union.subclass;public class Student extends Person{private String school;public String getSchool() {return school;}public void setSchool(String school) {this.school = school;}}

Person. hbm. xml
 
     
          
               
                
            
                   
               
            
                   
               
            
   
   
    
                       
  
 

Package com. atguigu. hibernate. union. subclass; import java. util. list; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import org. hibernate. service. serviceRegistry; import org. hibernate. service. serviceRegistryBuilder; import org. junit. after; import org. junit. before; import org. junit. test; public class HibernateTest {private SessionFactory sessionFactory; private Session session; private Transaction transaction; @ Beforepublic void init () {Configuration configuration Configuration = new Configuration (). configure (); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder (). applySettings (configuration. getProperties ()). buildServiceRegistry (); sessionFactory = configuration. buildSessionFactory (serviceRegistry); session = sessionFactory. openSession (); transaction = session. beginTransaction () ;}@ Afterpublic void destroy () {transaction. commit (); session. close (); sessionFactory. close () ;}@ Testpublic void testUpdate () {String hql = "UPDATE Person p SET p. age = 20 "Maid ();}/*** advantages: * 1. you do not need to use the reporters column. * 2. non-null constraints can be added for fields unique to subclass. ** disadvantages: * 1. redundant fields exist * 2. if fields in the parent table are updated, the update efficiency is low. * // ***** query: * 1. to query a parent record, You Need To summarize the records of the parent table and the child table before performing the query. poor performance. * 2. for subclass records, you only need to query a data table */@ Testpublic void testQuery () {List
 
  
Persons = session. createQuery ("FROM Person"). list (); System. out. println (persons. size (); List
  
   
Stus = session. createQuery ("FROM Student "). list (); System. out. println (stus. size ();}/*** insert operation: * 1. for subclass objects, you only need to insert records into a data table. * // @ Testpublic void testSave () {Person person = new Person (); person. setAge (11); person. setName ("AA"); session. save (person); Student stu = new Student (); stu. setAge (22); stu. setName ("BB"); stu. setSchool ("ATGUIGU"); session. save (stu );}}
  
 



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.