Hibernate code generation tools

Source: Internet
Author: User
Tags powerdesigner
1. Brief Introduction
Hibernate is an open Source code Object relationship ing framework, which implements lightweight object encapsulation for JDBC and provides the hql Query Language, enabling Java Program Developers can use the object programming thinking to manipulate the database as they wish. To use hibernate, you must configure the ing file-classmapping file and configuration file. Currently, Many hibernate Code Generate tools, such as XDoclet and sechmaexport, which officially comes with hibernate. However, they all have the following Disadvantages: only some basic input templates are provided, and users still need time to configure and modify them; automatic persistence classes and invokebean code generation are not provided; the graphic interface is not supported. The Code Generation for hibernatetestcase is not supported.

The Hibernate tool has the following features:
1. automatically generate a ing file based on the database model generated by UML.
2. Generate Hibernate Persistence classes based on UML.
3. Test the hibernate model.
4. Generate the automatic test code.
5. Integration with eclipse

The Hibernate code generation tool uses the powerdeigner-based model extension function to generate hibernate code. Powerdesigner (PD) is a first-class database modeling tool (E-R model design, physical model design), at the same time it for UML, reports, XML, team development (knowledge base repository) they all support quite well. All models can be converted to each other in a forward or backward manner. The PD model is composed of its meta model. In short, a metadatabase is a model that forms a model. Based on these meta-models, PD provides a GTL development language that can easily expand its own code templates and processes, and can also modify existing language models to meet requirements; PD supports Using VBScript to extend the language, change the PD model, and perform model detection. For eclipse, PD can also be quickly integrated and the Java language can be used to modify the PD model.

Note: GTL is an object-oriented scripting language that can be expanded on different metadata models and added: add functions such as file generation, prototype, menu, code template, and extended attributes. 1 is described in detail in the subsequent sections. Because the meta-model is object-oriented (for example, all classes and interfaces are inherited from the classifier meta-model), if a function is extended in classifier, the model inherited from it has such functions and scripts, and can overwrite such functions to implement the concept of polymorphism.

Open the extended model editing window: Select modelextended model definition, and select import extended model definition (penultimate button) on the toolbar in the pop-up window to load the existing model, you can also create an extension model (select the Add row button and double-click the first column of the model to be edited in the table to bring up the interface shown in 1)

To help readers better understand the concept of the PD meta-model, the meta-model architecture used by the hibernate code generation tool is captured, as shown in figure 2. You can find <PD installation path> \ examples \ metamodel. OOM in the installation directory of PD. The chart is stored in pdoom and its name is class objects.
For space reasons, we will extract typical code and models to explain how to design the hibernate code generation tool.

Overall architecture process generated by hibernate code (activity diagram)

The principle of automatic file generation by Hibernate is:
1) The subclass ing information is attached to the root class ing file (root class). That is, the subclass will not generate code independently.
2) No code is generated for the value-type class and non-persistent class.
3) do not generate code for non-class objects (such as interfaces)

Where:
Check models in digoal: hibernate model detection to determine whether the domainmodel complies with the hibernate syntax. If an error occurs, the PD throws an error message (automatic error correction is provided)
Generate configuration file: select model attributes (model-> model properties). You can set the configuration information under extended attribute. PD generates a configuration file based on the configuration information.
Get each class in digoal: This is a mechanism of PD. It automatically obtains all model elements in UML, and according to the extended attributes of each model (profile \ generated file) to generate code files.
Generate basic mapping: Basic ing of a class, including ID, composite-ID, and propery.
Get subclass style: Child class ing, recursively obtained.
Generate join: When the persistent class corresponds to the ing of multiple tables, you need to use join to specify.
Generate Association mapping: determines the ing Based on the association type between classes. This tool supports one-to-one, one-to-least, minus-to-one, attributes-to-attributes (set based on the multiplicity under the detail label of association properties). Set, set, list, bag, And idbag are supported (Set Based on containtype ).
Get Java code information: the extension model is based on the existing language model, that is, the extension model can obtain the language model templates and various settings, for the Java persistence class of hibernate, we only need to add the getter and setter corresponding to the attribute under the Java code. % Source %
Generate invoke Bean: generate the crud function of hibernate.
Generate Test Case: hibernate test case code. The generated random data is used to verify the correctness of hibernate.
Generate log4j: generate the log4j configuration file
Generate ant build. XML: When you set ant to true in Options Under Generation files and configure the path of ant Lib, Hibernate tools will generate build. XML, Then ant will be automatically run to test hibernate. The generated results will be stored in logs by log4j.

2. Key Technical Points
O/R Mapping
PD has been strengthening o/R Mapping since 8.0. In addition to code model generation, PD also generates o/R Mapping definitions, such as generating ejb cmp components. You can define o/R Mapping to establish the relationship between OOM and PDM.
PD supports three methods of O/R Mapping:
The first is to automatically establish a connection by PD after converting from a class chart to a data model (applicable to the top-down design process );
The second is to automatically establish a connection from the PD after converting the data model into a class chart (applicable to the bottom-up design process );
The third is to manually create a class chart and data model (applicable to synchronous design or later modifications)
Creation process:
First, select the class graph and design the pojo class. Then, select Tools> generate physical data model. In the displayed window, select the detail tag and select the O/R Mapping option. You can choose whether to update an existing database or create a new database.
The second type: similar to the first type of creation process, it is changed to generate object-oriented model in the database model.
Third, you must first create a datasource, find the class file in the left-side workspace tree directory, right-click and select new \ data source, and select from the models tab in the pop-up window, select the database model to be associated. Open the class attributes in the class model (double-click the class for which you want to create O/R Mapping), select the mapping tab, and click the button to add the datasource you just created. Click "add ing" to create a data table.
You can add multiple tables, which indicates that a class may correspond to the ing of multiple tables. hibernate ing should be indicated by the join attribute.
Note: When you create a classsource, PD automatically creates attributemapping based on the class attributes and table fields. Of course, you can also modify the butemapping ing on the attributemapping attribute page.
As you know, the hibernate ing file must contain table expressions (such as column and property attributes). In PD, you can easily obtain the corresponding table information through mapping in the meta-model. Figure 4 shows the O/R mapping meta model used in GTL.
O/R Mapping architecture diagram:

Architecture Description:
1) Association:
In the asoociation meta-model, you can use mappings to obtain associationmapping (the datasource selected by the user under mapping for). Each associationmapping has sourceclassifiers, which is a ing set in the asoociationsource tag, 5. Elements in the sourceclassifiers set, that is, the reference meta-model in the data model, as shown in figure 6.
Because PD can add other references and tables in the Data Model under association mapping, it adopts type judgment when generating hibernate code to avoid errors caused by Type mismatch.


Implementation Code (Table ing): (Note: The appendix section describes some GTL syntaxes)
.

Implementation Code (referencecolumnhelper template ):

2) class and attribute
The method for obtaining database models is similar to association. In o/R Mapping, the sourcefeature of classmapping is equivalent to the data table. The sourcefeature of attributemapping is equivalent to the column information in the data table. Figure 7 shows the structural diagram of the database metadata model used during writing.
Implementation Code (get the table information corresponding to the class)

Mappings. First. classsources indicates the table set under the current data source.
Implementation Code (get the column information corresponding to attribute)
Example: % attributemappings. First. sourcefeature. Code %
% Attributemappings. First. sourcefeature % corresponds to the column Meta Model in figure 7.

Extended attribute
In the hibernate generation tool, a large number of options are required for user selection or input. In this case, we can use the extended attribute provided by PD to extend the attributes of the model. In addition to dependency and generalization, other UML models have extended attributes for extension.
Set extended attribute step: Enter the extension model editing window, select a metamodel under profile, right-click and select extended attribute. PD already provides multiple default options (with parentheses ), of course, you can add your extended attribute type (right-click the shared directory under profile and select extended attribute type, and set the column content and default value on the right. After the settings, the reader can reference the custom type in the extended attributes of the model. In GTL, you can use % property name % to reference the selected value of the current user, or you can use % Template Name % to reference the GTL template (readers can select the template and press F12 to redirect ).

Check Model
Considering that because of the domainmodel created based on UML, some syntactic errors are inevitable for the hibernate syntax. For example, if Association is set up between two classes, but no reference is found between the corresponding tables, or there is a reference but there is no column under joins, then we should give an error warning, prompting the user to check.
Taking associationcheck as an example, we will introduce how to implement custom check.
Open the hibernate extension model, select profile \ Association, and right-click New \ custom check. On the right side, you can see four tabs, as shown in figure 9.


Check Script: used to detect the model. % check % = true. No error message is displayed.
AutoFix Script: used to automatically fix model errors. % fix % = false indicates that the error is not fixed. When the PD detects an error, you can right-click the error and choose automatic correction. For automatically fixed errors, a "+" sign is added in the lower-right corner of the icon. For example, it indicates that the PD is fixed based on AutoFix script.
Global Script: used to store global functions. It can be called in any metadatabase check model.
Implementation Code
Check Script: used to check whether refence is correctly established.

Note: PD detects each model (including Package). If you want to use a program to control whether the model is detected, you only need to add % check % = true (indicating that the verification is correct and skipped) in the syntax section that meets the conditions.

Persistent class persistent class
For pojo persistent classes, the getter and setter functions must be added for each of their class attributes. The extension model is based on the language model. That is to say, templates and other content in the language model can be overwritten and overwritten in the extension model. Therefore, the hibernate extension model uses the overload method to extend the Code Generation of the Java language model and retain the original Java code, add your own getter and setter templates to the extended model.
In the Java language model, code generation relies on the % source % template to complete Java code. At the same time, there is a % initializers % template to implement initialization after attribute is completed, therefore, the % initializers % template is rewritten in the same position (class meta-model). The Code is as follows:

Add the getterfunction and setterfunction templates to the attribute meta-model. The Code is as follows:

Add the persistent class generated files in the class meta-model, and enter % source % in the template editing box.

Generated files
PD provides the file generation function in each metadata model. Right-click the class metamodel and choose generated files. In the right window, enter the generated file name under file name. Because the file name of the hibernate ing file is the same as the class name, enter % mappingfilename %, create the mappingfilename template, and enter % code %. HBM. xml.
Note: All metadata models inherit from namedobject (namedobject inherits from baseobject) and store standard attributes of various metadata models in namedobject, such as model name) code, comments, and descriptions. Therefore, to get the class name, enter % code % under the class meta model. HBM. XML, the PD will create a corresponding file for each Class Based on the code name (the premise is that the class can be generated, that is, it has been persistent ).

Model
The model meta-model mainly configures the connection information of configuration mapping, such as JDBC. The method used is the extended attribute and mapping code template. For space reasons, you can refer to this Article or run pdvbs11.chm In the PD installation directory for help.

Task
The task is activated after the code is generated, and the PD executes the selected task in order. Added the hibernate model, the ant lib path, the generated directory name, and other options. Create a new option under generation \ options, similar to extended attribute. When you call the options Option, enter the following code: % genoptions. Option name %.
For tasks, you want to use ant's build. xml configuration for automatic testing. In PD, the Java language model has provided ant build. the Automatic Generation and reserved interfaces of XML (three templates: customexecutetarget, customerproperties, and customtaskdefs) are designed to enable the extension model to be overloaded, interested readers can view the Java language model (mongoageedit current object language, browse Java: Profile \ model \ Templates \ ant \ anttemplate ).

Create a task:
Right-click generation \ Tasks and select new. Enter the Task Name (the display name of the actual execution) and name it "Run unit test. Select the created command in the following table. If the command is not created, you can create a new command on commands.
Run unit test command code:

Note:
. Execute_command is a macro command used to execute external programs.
. Execute_command '(' <cmd> [',' <ARGs> [',' <mode>] ')'
The first parameter is the main command, which is cmd.
The second parameter is the main command parameter. Here is/k ant. Bat JUnit
The second parameter is the MPs queue type. PD provides two methods: pai_shellexecute and pai_pipeoutput. The former adopts an independent process mode, and the latter blocks the PD until the task is completed, and the result is displayed in the output window of the PD, as shown in 10.

3. Conclusion
Powerdesigner is a flexible software modeling tool. Based on its meta-model, you can use different languages (GTL, VBScript, Java, C #, etc.) as you like) to design your own code generation tools, even language models and reports. This article has only played a leading role. I believe that with experience in the field, readers can certainly design code generation tools that are more suitable for themselves, simplify the process, reduce costs, and accelerate development.

Appendix:
some GTL syntaxes are listed. You can also refer to the pdvbs11.chm file under the PD installation directory or the Sybase official website.
1. resource file
readers can refer to the existing model of pd11:
you can find the existing Extension Model Under \ resource files \ extended model definitions under the installation directory; find the VBScript code in \ VB scripts under the installation directory, and find out how to use other languages such as Java, C # To obtain the metamodel for your own code generation tools under the OLE Automation directory; find the language model in the library directory. Find the PDF document in the printable docs directory (we recommend that you refer to the advanced user documentation. pdf document ).
2. syntax
. set the variable
the variable name must be % encapsulated, that is, % variable name %
global variable
variable region
In short, when a region is created (such as a loop or another template ), you must use outer to call variables outside the region. variable name.
B. loop
C. judgment condition
D. set
E. special symbol

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.