The relationship between classes, we can be divided into four kinds: association, dependency, inheritance, implementation. And the relationship between the entity classes we're talking about often comes up with two kinds of relationships: association and inheritance, and why are the other two not very common? First, the dependency between classes is a weaker relationship, which can be understood in code as a reference or call to another class on the parameters of a method of a class or within a method, a reference class or a class that does not belong to a variable type of the original class, and there is no method between entity classes, and there is no dependency. The implementation describes the relationship between the class and the interface, the general interface is used to define the method, that is, the equivalent of defining some specifications, do not implement.
In the previous articles, we learned and learned how to use hibernate to make associative mappings between entity classes, and it can be said that such associations are often used in projects, and we often consider the case of entity class inheritance in our projects. Today we'll talk about how to use hibernate to implement an inheritance mapping between entity classes.
Principle Analysis
Hibernate provides three strategies to implement inheritance mappings for classes: A table of inheritance trees, a table of classes, a table for a specific subclass.
1. A tree to inherit a table
First look at the effect the first strategy will achieve:
Look at our mapping file:
<?xml version= "1.0"?><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hib Ernate-mapping-3.0.dtd "><hibernate-mapping package ="Com.tgb.hibernate"> <class name="Animal" lazy="false"> <ID name="id"> <generator class="native" /> </ID> <!--Define the identification field, placed after the ID label-- <discriminator column="type" type="string" /> < property name="name" /> < property name="Sex" /> <!--Two subcategories: Pig,bird, determine the value of the authentication field on the subclass- - <subclass Name="Pig" discriminator-value="P"> < property name="Weight" /> </Subclass> <subclass Name="Bird" discriminator-value="B"> < property name="height"></Property > </Subclass> </class></hibernate-mapping>
The first scheme uses the subclass tag mapping subclass and uses the discriminator discriminator to block the molecular class.
2. A table of a class
As follows:
The mapping file is as follows:
<?xml version= "1.0"?><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hib Ernate-mapping-3.0.dtd "><hibernate-mapping package ="Com.tgb.hibernate"> <class name="Animal" table="T_animal" lazy=" False "> <ID name="id"> <generator class="native" /> </ID> < property name="name" /> < property name="Sex" /> <!--associated subclass tags, similar to basic mapping <joined-subclass name="Pig" table="T_pig"> <key column="pid" /> < property name="Weight" /> </joined-subclass> <joined-subclass name="Bird" table="T_bird"> <key column="bid" /> < property name="height" /> </joined-subclass> </class></hibernate-mapping>
The second scenario uses the Joined-subclass tag to map the subclass, often see join this word, think of SQL connection query, here also have similar wonderful AH.
3. A specific sub-category A table
As follows:
The mapping file is as follows:
<?xml version= "1.0"?><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hib Ernate-mapping-3.0.dtd "><hibernate-mapping package ="Com.tgb.hibernate"> <class name="Animal" table="T_animal " abstract ="true"> <ID name="id"> <generator class="Assigned" /> </ID> < property name="name" /> < property name="Sex" /> <!--Union sub-class - <union-subclass name="Pig" table="T_pig"> < property name="Weight" /> </union-subclass> <union-subclass name="Bird" table="T_bird"> < property name="height" /> </union-subclass> </class></hibernate-mapping>
The third scenario is mapped using the Union-subclass Tag Association subclass, which adds the attribute union of the parent class to the child class, which is mapped to the table field, that is, multiple sub-class tables have the same fields structure.
Contrast
In three implementation strategies, the first strategy, the table structure has redundant fields, does not conform to the basic three-paradigm requirements, but the query efficiency is high; the second strategy, storage is clear, sub-class table only holds the extended attribute, but if the inheritance hierarchy is deep, the query will be associated with a large number of tables;
There are three ways to be good and bad, and you can choose which strategy to use only with experience and specific needs.
Operation Example
After understanding the implementation principle of the inheritance map, we can touch a new concept-polymorphic query: Hibernate can use instanceof to identify real types when loading data. Load, by default, does not support polymorphic queries.
The sample code is as follows:
To save the data method:
Public void Saveanimal() {Session session =NULL; Transaction tx =NULL;Try{session = Hibernateutils.getsession (); tx = Session.begintransaction (); Pig pig =NewPig (); Pig.setname ("PIG1"); Pig.setsex (false); Pig.setweight ( $); Session.save (pig); Bird Bird =NewBird (); Bird.setname ("Bird1"); Bird.setsex (true); Bird.setheight ( -); Session.save (bird); Tx.commit (); }Catch(Exception e) {E.printstacktrace ();if(tx! =NULL) {tx.rollback (); } }finally{hibernateutils.closesession (session); } }
Examples of test polymorphic queries are as follows:
Public void TestLoad() {Session session =NULL; Transaction tx =NULL;Try{session = Hibernateutils.getsession (); tx = Session.begintransaction (); Animal Animal = (Animal) session.load (Animal.class,1);if(Animal instanceof Pig) {System. out. println (Animal.getname ()); } tx.commit (); }Catch(Exception e) {E.printstacktrace ();if(tx! =NULL) {tx.rollback (); } }finally{hibernateutils.closesession (session); } }
This method will not print any content under the default configuration.
We set the class tag property of the map file animal to "false" and the console will print the animal name.
Summarize
At this point, hibernate in the inheritance map is finished, speaking so half a day, in fact, is to do one thing, that is, how to inherit the object model corresponding to the database storage and subsequent reading, modification and other operations. Hibernate provides us with a number of solutions to select the most appropriate strategy in the actual project, depending on the specific situation (the number of data stored, the hierarchy of inheritance, the efficiency requirements, etc.). With the technical basis, is the experience, thinking.
Hibernate (eight)--inheritance mapping