An Inheritance mapping learning tutorial In the Java Hibernate framework _java

Source: Internet
Author: User

One, inheritance mapping
inheritance is an object-oriented feature that implements the use of code, as well as inheritance in relational models, which can be viewed as an enumeration relationship in which many subtypes can be enumerated, and these subtypes and parent objects form inheritance relationships. Most of them can be enumerated as an inheritance map, so this enumeration relationship can be seen as an inheritance map, for example, an animal is an abstract class, which is the parent of other animals such as pigs and cats, which is an inheritance relationship, as shown below:

This kind of inheritance map generates a table after it is transformed into a relational model, so how does this table differentiate between the two types? With a relational field, you need to add a Type field to the table and use keywords to indicate the type of object. So the object model in the above diagram corresponds to the following table structure:

When generating a table structure, you need to add the corresponding field type, so you need to add the corresponding mapping discriminator in the mapping file, where you need to use the Discriminator-value property.
1. class files
There is no need to pay attention to the class file, the inheritance relationship between the attention when writing.
Listing one: Animal class code, you just need to add the basic attributes.

Package com.src.hibernate; 
 
public class Animal { 
 
 //id number 
 private int id; 
 public int getId () {return 
 ID; 
 } 
 public void setId (int id) { 
 this.id = ID; 
 } 
 
 Name 
 private String name; 
 Public String GetName () {return 
 name; 
 } 
 public void SetName (String name) { 
 this.name = name; 
 } 
 
 Gender 
 private Boolean sex; 
 public Boolean issex () {return 
 sex; 
 } 
 public void Setsex (Boolean sex) { 
 this.sex = sex; 
 } 
} 

Listing two: Bird and pig classes, add basic attributes, and inherit the animal class.

Package com.src.hibernate; 
public class Bird extends Animal { 
 
 //height 
 private int height; 
 public int getheight () {return 
 height; 
 } 
 public void setheight (int height) { 
 this.height = height; 
 } 
 
} 
 
Package com.src.hibernate; 
public class Pig extends Animal { 
 
 //weight 
 private int weight; 
 public int getweight () {return 
 weight; 
 } 
 public void setweight (int weight) { 
 this.weight = weight; 
 } 
} 

2. Mapping file
in the mapping file, you need to add a corresponding mapping, which only needs to add a mapping file, because only one table is generated, the corresponding subclass mapping is added to the mapping file, and the <subclass> tag is added to the tag to add the discriminator Discriminator-value , the Discriminator property indicates what type of writing is indicated when the data is written in the database, as follows:

 <?xml version= "1.0"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hiber 
 Nate-mapping-3.0.dtd ">  
 

3. Analysis Results
the generated MySQL database table not only adds the basic properties of the animal, but also adds pig and bird properties, because the added attributes are written out in the mapping file <subclass>, and the corresponding discriminator properties are added. Therefore, the corresponding authentication columns are added to the database, and the resulting table structure is shown as follows:

Second, data operation

1. Write Data
It is necessary to note that the operations in the class are used in data read and write operations

public void Testsave () {session 
 Session=null; 
 try{ 
 //Create Session Object 
 session=hibernateutils.getsession (); 
 Open transaction 
 session.begintransaction (); 
 
 Pig pig=new Pig (); 
 Pig.setname ("Piggy Pig"); 
 Pig.setsex (true); 
 Pig.setweight (); 
 Session.save (pig); 
 
 Bird bird=new Bird (); 
 Bird.setname ("Xiaoniaoniao"); 
 Bird.setsex (true); 
 Bird.setheight (m); 
 Session.save (bird); 
 
 Session.gettransaction (). commit (); 
 catch (Exception e) { 
 e.printstacktrace (); 
 Session.gettransaction (). rollback (); 
 } finally{ 
 Hibernateutils.closesession (session); 
 } 
 
 

2. polymorphic Query--get and HQL

Basic Query method, only need to use the load and get method, here focus on the polymorphic query. polymorphic query means that hibernate can be used to identify the real type of object when loading object can be polymorphic query instanceof.
Note: polymorphic queries do not support deferred loading, which means that if you use the Load method, you need to set the delay load to false in the mapping file.

3.load Delay Loading
load supports deferred loading, which actually generates an object's proxy when the object is loaded, so you need to set the deferred load to false in the mapping file when using polymorphic queries, as follows:

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

The load load method, which supports polymorphic queries in the configuration file with load loading, sets the deferred load to false in the profile, so the Load method is used here to load the corresponding object class.

public void TestLoad () {session 
 Session=null; 
 try{ 
 session=hibernateutils.getsession (); 
 Session.begintransaction (); 
 
 Animal ani= (Animal) session.load (animal.class,1); 
 System.out.println (Ani.getname ()); 
 Because the load defaults to support lazy, we see the animal proxy 
 //So the instanceof cannot identify the true type pig 
 //So the load is not supported in this case by polymorphic queries 
 (ANI instanceof Pig) { 
 System.out.println ("I'm a piggy pig!") "); 
 } else{ 
 System.out.println ("I'm not a pig!") "); 
 } 
 Session.gettransaction (). commit (); 
 catch (Exception e) { 
 e.printstacktrace (); 
 Session.gettransaction (). rollback (); 
 } finally{ 
 Hibernateutils.closesession (session); 
 } 
 

4.HQL Query
HQL Support polymorphic query, this is mainly because the query is a real object, does not return a proxy, so HQL support polymorphic query, in addition to the query need to pay attention to query statements do not use the table name, but to use the class name, Hibernate maps it to the corresponding table name based on the class name, as follows:

public void TestLoad5 () {session 
 Session=null; 
 try{ 
 session=hibernateutils.getsession (); 
 Session.begintransaction (); 
 
 List<animal> list=session.createquery ("from Animal"). List (); 
 For (iterator Iter=list.iterator (); Iter.hasnext ();) { 
 Animal a= (Animal) Iter.next (); 
 if (a instanceof Pig) { 
 System.out.println ("I am a piggy pig!") "); 
 } else{ 
 System.out.println ("I'm not a pig!") "); 
 } 
 } 
 Session.gettransaction (). commit (); 
 catch (Exception e) { 
 e.printstacktrace (); 
 Session.gettransaction (). rollback (); 
 } finally{ 
 Hibernateutils.closesession (session); 
 } 
 

Query results:

Hibernate:select animal0_.id as id0_, animal0_.name as name0_, animal0_.sex as sex0_, animal0_.weight as weight0_, animal 0_.height as height0_, Animal0_.type as type0_ from T_animal animal0_ 
I'm a pig! 
I'm not a pig! 
I'm a piggy pig! 
I'm not a pig! 

Three, inheritance mapping three kinds of strategy
1. Each class hierarchy a table (table per class hierarchy)

Suppose we have interface payment and several of its implementation classes: Creditcardpayment, Cashpayment, and Chequepayment. The mapping code for the "Table per class hierarchy" (Table from class hierarchy) is shown below:

<class name= "Payment" table= "Payment" > 
 <id name= "id" type= "long" column= "payment_id" > 
 < Generator class= "native"/> 
 </id> 
 <discriminator column= "Payment_type" type= "string"/> 
 <property name= "Amount" column= "Amount"/> 
 ... 
 <subclass name= "creditcardpayment" discriminator-value= "credit" > 
 <property name= "Creditcardtype" column= "Cctype"/> ... 
 </subclass> 
 <subclass name= "cashpayment" discriminator-value= "CASH" > 
 ... 
 </subclass> 
 <subclass name= "chequepayment" discriminator-value= "cheque" > 
 ... 
 </subclass> 
</class> 

Using this strategy requires only a single table. It has a big limitation: requiring those fields defined by subclasses, such as Cctype, that cannot have non-null (NOT null) constraints.

2. A table for each subclass (table per subclass)

For several classes in the example above, the mapping strategy of "one table per subclass" is used, as shown in the following code:

<class name= "Payment" table= "Payment" > 
 <id name= "id" type= "long" column= "payment_id" > 
 < Generator class= "native"/> </id> <property name= "Amount" column= 
 "Amount"/> 
 ... 
 <joined-subclass name= "creditcardpayment" table= "credit_payment" > 
 <key column= "PAYMENT_ID"/> 
 ... 
 </joined-subclass> 
 <joined-subclass name= "cashpayment" table= "cash_payment" > 
 <key Column = "payment_id"/> <property name= "Creditcardtype" column= "Cctype 
 "/> 
 ... 
 </joined-subclass> 
 <joined-subclass name= "chequepayment" table= "cheque_payment" > 
 <key column= "payment_id"/> ... 
 </joined-subclass> 
</class> 

Four sheets are required. Three subclass tables are associated with a superclass table through a primary key (and thus the relational model is actually a one-to-one association).

3. Each subclass a table (table per subclass), using the identification Mark (discriminator)

Note that for "one table per subclass" Mapping strategy, hibernate implementations do not need to distinguish fields, while other object/relational mapping tools use a different implementation method than Hibernate, which requires a type-distinguished field in a superclass table (type discriminator column). Hibernate's approach is more difficult to implement, but from a relational (database) Point of view, it is arguably more correct. If you are willing to use a "each subclass table" strategy with a distinguished field, you can use <subclass> and <join> together, as follows:

<class name= "Payment" table= "Payment" > 
 <id name= "id" type= "long" column= "payment_id" > 
 < Generator class= "native"/> 
 </id> 
 <discriminator column= "Payment_type" type= "string"/> 
 <property name= "Amount" column= "Amount"/> 
 ... 
 <subclass name= "creditcardpayment" discriminator-value= "credit" > 
 <join table= "Credit_payment" > 
 <property name= "Creditcardtype" column= "Cctype"/> 
 ... 
 </join> 
 </subclass> 
 <subclass name= "cashpayment" discriminator-value= "CASH" > 
 <join table= "Cash_payment" > ... 
 </join> 
 </subclass> 
 <subclass name= "chequepayment" discriminator-value= "cheque" > 
 <join table= "cheque_payment" fetch= "select" > ... 
 </join> 
 </subclass> 
</class> 

The optional Declaration, fetch= "select", is used to tell hibernate that when querying a superclass, do not use an outer join (outer join) to crawl the data of a subclass chequepayment.

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.