Eclipse quickly hibernate--4. Inheritance Mappings (1)

Source: Internet
Author: User
Tags define generator sql mysql net one table variables version
Inherit the eclipse quick-start hibernate--1 before. Three articles, such as getting started, have already talked about getting started with hibernate and using tools to create them. This article is mainly about the inheritance mapping in Hibernate.    For related configuration Please refer to the first three articles. If the object in the program contains an inherited relationship, there are three strategies in hibernate that map the relationship to the datasheet: · One table per class hierarchy (table each class hierarchy) · One table per subclass (table subclass) · Each concrete Class A table (table per concrete Class) (some restrictions) the way each class hierarchy is a table is to store all objects that inherit the same parent class in the same table in order to do this, You need to use a recognition field in a table to indicate that a column (row) belongs to a subcategory or a parent category, and we will explain this method first in this topic.  1. Create Project ·   Create a new Java project: Inheritancemapping, and note that creating a separate source folder and output folder is selected, adding the user library: Hibernate.  2. Writing class documents · Create a new class, package Name: Javamxj.inheritance.one, class name: Animal. You then add variables to the generated code, and then use "Generate Getter and Setter", specifically with Eclipse fast-start hibernate--1. Getting started with the same way as editing User.java in the article.
Animal.java


* * Hibernate-Inheritance mapping (one table per class level) * Create date 2005-4-9 * @author javamxj (share java Fun) * @link blog:htpp://javamxj.mblogger.cn * HTP p://blog.csdn.net/javamxj/*/package javamxj.inheritance.one;/** * @hibernate. Class * table= "Animal" * Discriminator-value= "Animal" * @hibernate. Discriminator * column= "animal_type" * type= "string" * length = "Ten" */public AB Stract class Animal {private Long id;private String name;/** * @hibernate. ID * column= "id" * generator-class= "Hilo" * UNSA Ved-value= "null" */public Long getId () {return ID;} public void SetId (Long id) {this.id = ID;} /** * @hibernate. Property * length = ' */public ' String getName () {return name;} public void SetName (String name) {this.name = name;} public abstract void MakeSound ();}

·  This class is a parent class, and it is worth noting that a discriminator tag is added to the class hierarchy and used to define a field "Animal_type" that identifies a column (row) as belonging to a subcategory or parent category. · Sub Class Cat.javaCat.java
Package javamxj.inheritance.one;/** * @hibernate. Subclass * discriminator-value= "cat" */public class Cat extends Animal { Private String furcolor;public void MakeSound () {System.out.println ("Meow");} /** * @hibernate. Property * length = ' */public String getfurcolor () {return furcolor;} public void Setfurcolor (String furcolor) {furcolor = Furcolor;}}
· Sub Class Dog.javaDog.java
Package javamxj.inheritance.one;/** * @hibernate Subclass * discriminator-value= Dog */public class Dog extends Animal { Private String category;public void MakeSound () {System.out.println ("barking");} /** * @hibernate. Property * length = ' */public String getcategory () {return category;} public void Setcategory (String category) {this.category = category;}}
·  These two subclasses are simple, note the hibernate.subclass tag of the addition, and specify their recognized fields.  3. Build file Build.xml In the project root directory to establish a build.xml, to note that the environment variables and database settings to meet their actual configuration, where the library file directory settings is "D:/java/hibernate/lib", reference article " Eclipse quickly hibernate--1.  The settings in the Getting Started instance. · In MySQL, you need to set up a hibernatetest database, in order to solve the Chinese problem, the use of GBK encoding, pay attention to "&", this is because Xdoclet generate hibernate configuration file, will lose an "amp;"  String (a small bug). · Here I use the "Hibernatedoclet" task in Build.xml to generate the "hibernate.cfg.xml" configuration file directly.
Build.xml


<?xml version= "GBK" Help "><project" name= "1.0" encoding= "Hibernate"? default= basedir= "." ><!--environment settings, can be based on their own actual configuration change * * * * *--><!--source file directory, you can-> the project->java build path Changes--><property Name= "Src.dir" value= "./src"/><!--the Output class file directory, which can be changed through the Project-> property->java build Path--><property name= " Class.dir "value="./bin "/><!--library file directory--><property name=" Lib.dir "value=" D:/java/hibernate/lib "/>< !--the database settings, can be based on their own actual configuration change * * * * * *--><property name= "Hibernate.dialect" value= " Net.sf.hibernate.dialect.MySQLDialect "></property><property name=" Hibernate.driver "value=" Com.mysql.jdbc.Driver "></property><!--&--><property name=" Hibernate.jdbc.url "value=" JDBC: MYSQL://LOCALHOST:3306/HIBERNATETEST?USEUNICODE=TRUE&AMP;CHARACTERENCODING=GBK "></property>< Property Name= "Hibernate.username" value= "root" ></property><property name= "Hibernate.password" Javamxj "&GT;&LT;/PROPERTY&GT;<property name= "Hibernate.show.sql" value= "true" ></property><!--define classpath--><path id= " Project.class.path "><fileset dir=" ${lib.dir} "><include name=" *.jar Pathelement location= "${class.dir}"/></path><!--*************************************************** --><!--Use instructions--><!--**************************************************************--> <target name= "Help" ><echo message= "exploiting tools Hibernate"/><echo message= "------------------------------ -----"/><echo message=" "/><echo message=" provides the following tasks: "/><echo message=" "/><echo message=" GENERATE-HBM--> run Hibernatedoclet, generate Hibernate class mapping file "/><echo message=" Schemaexportt--> run Schemaexport, Generate datasheet using Hbm.xml file "/><echo message=" "/></target><!--******************************************* --><!--hibernatedoclet task--><!--***********************************--><target name= "GENERATE-HBM" ><echo message= runs Hibernatedoclet, generating Hibernate class's mapping file "/><taskdef name=" Hibernatedoclet "Classname=" Xdoclet.modules.hibernate.HibernateDocletTask "Classpathref=" Project.class.path "></taskdef>
· Well, as long as these four files are enough, the others will be automatically generated. The entire project is structured as follows: 4.  Run Tasks · Double-click the "GENERATE-HBM" task, you will find in the package more than a Animal.hbm.xml file, in the SRC directory will be more than a hibernate.cfg.xml file, if not, press the F5 key to refresh (it is recommended to open Eclipse's preferences dialog box, check the "Automatically refresh Workspace" and "save automatically before building" in the workbench so that you don't have to refresh it every time.
Animal.hbm.xml


<?xml version= "1.0" encoding= "GBK"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 2.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-2.0.dtd ">
Hibernate.cfg.xml
<?xml version= "1.0" encoding= "GBK"? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 2.0//en" "http:// Hibernate.sourceforge.net/hibernate-configuration-2.0.dtd "><!--generated file-do not edit! -->· Double-click the "Schemaexport" task to produce a "schema-export.sql" file in the project root. Schema-export.sqldrop table if exists animaldrop table if exists hibernate_unique_keycreate table Animal (ID bigint not NULL, Animal_type varchar (a) not NULL, name varchar (in), Furcolor varchar (in), category varchar (), primary K  EY (ID) CREATE TABLE Hibernate_unique_key (Next_hi integer) insert into Hibernate_unique_key values (0) ·  When you switch to a database, you will find that you have automatically generated the Datasheet animal (table Hibernate_unique_key is generated by using the Hilo Primary key policy).  5. Test Procedures · OK, a new Demo.java class under the package Javamxj.inheritance.one is very simple, the first half is to add the data, the second half is a simple test.
Demo.java


Package Javamxj.inheritance.one;import Java.util.iterator;import Java.util.list;import Net.sf.hibernate.hibernateexception;import Net.sf.hibernate.session;import net.sf.hibernate.SessionFactory; Import Net.sf.hibernate.transaction;import Net.sf.hibernate.cfg.configuration;public class Demo {public static void Main (string[] args) {try {new Demo ();} catch (Hibernateexception He) {he.printstacktrace ();}} Public Demo () throws hibernateexception {sessionfactory sf = new Configuration (). Configure (). Buildsessionfactory (); Session Sess = Sf.opensession (); Transaction tx = null;try {tx = Sess.begintransaction (); Cat cat = new Cat (), Cat.setname ("small white"), Cat.setfurcolor ("white"), Sess.save (cat);D og Dog = new Dog ();d og.setname ("small Black"); Dog.setcategory ("Kyung-ba Dog"); Sess.save (dog); Tx.commit (); catch (Hibernateexception e) {if (tx!= null) Tx.rollback (); throw e;} finally {sess.close ();} Sess = Sf.opensession (); tx = null;try {tx = Sess.begintransaction (); List animals = sess.find (' from ' + Animal.class.getName ()); for (IteraTor it = Animals.iterator (); It.hasnext ();) {Animal Animal = (Animal) it.next (); System.out.println ("Animal" + animal.getname () + "' Is the class is:" + animal.getclass (). GetName ()); System.out.print ("squeal:"); Animal.makesound (); Tx.commit ();} catch (Hibernateexception e) {if (tx!= null) Tx.rollback (); throw e;} finally {sess.close ();}}}

·  Running this class, the console output is as follows: ·  At the same time, the data table generates the following data: Notice the part of it that is "NULL". · The final project structure is as follows: summary: Advantages: · Simple to achieve. · Supports polymorphism--when an object role changes, or when multiple roles exist. · The report operation is simple: All information is included in the table. Disadvantages: · Increase the coupling in the class hierarchy. An increase in the properties of any class in a class hierarchy results in a change to the table, and a modification of a subclass property affects the entire hierarchy, not just the subclass. · Wasted some database space. The amount of wasted space depends on the depth of the inheritance hierarchy. The deeper the hierarchy, the more different attributes, the greater the complete collection of attributes, and the more waste of space.  You may need to specify a specific role. Reference: · HIBERNATE-Java-compliant relational database Persistence (8th chapter) · Hibernate Simplified Inheritance mapping · Mapping Objects to relational databases:o/r Mapping in detail Mapping objects to relational databases the next article will talk about the strategy of a table for each subclass.

Related Article

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.