JBoss.orgCommunity Documentation
This chapter will introduce you to the functionality that Hibernate Tools provide within Eclipse. That is a set of wizards and editors for simplifying the work with Hibernate.
Hibernate Eclipse Tools include wizards for creating Hibernate mapping files, configuration files (.cfg.xml), revenge.xml as well as wizards for adjusting Console Configuration and Code Generation. Special structured and XML editors, editors for executing HQL and Criteria queries are also provided in Hibernate Console. Refer to Key Features section to find all benefits that you can take advantage of while using the tools within Eclipse.
Please note that these tools do not try to hide any functionality of Hibernate. The tools make working with Hibernate easier, but you are still encouraged/required to read the Hibernate Documentation to fully utilize Hibernate Tools and especially Hibernate it self.
You can download example projects which are used as base for this chapter.
JPA base project is available here and base Java project is situated here.
Also you need start database.
How to run database you can know in Getting Started Guide.
Hibernate mapping files are used to specify how your objects are related to database tables.
To create basic mappings for properties and associations, i. e. generate .hbm.xml files, Hibernate Tools provide a basic wizard which you can bring up by navigating New > Hibernate XML mapping file.
At first you'll be asked to select a package or multiple individual classes to map. It's also possible to create an empty file, don't select any packages or classes and an empty .hbm will be created in the specified location
With depth control option you can define dependences depth for choosing classes (it means to set level of references which is used to collect linked classes to the selection).
The next wizard page lists the mappings to be generated. As you see Customers, Orders, Productlines and Products classes added under depth control driving.
This wizard page outputs a generated .hbm files preview.
Pressing Finish creates the files.
To be able to reverse engineer, prototype queries, and of course to simply use Hibernate Core a hibernate.properties or hibernate.cfg.xml file is needed. The Hibernate Tools provide a wizard for generating the hibernate.cfg.xml file if you do not already have such one.
Start the wizard by clicking New > Other (Ctrl+N) , then Hibernate > Hibernate Configuration File (cfg.xml) and press Next or on a web Seam project in the Web Projects view WebContent -> New -> File -> Hibernate Configuration 3.0 . After selecting the wanted location for the hibernate.cfg.xml file, you will see the following page:
The contents in the combo boxes for the JDBC driver class and JDBC URL change automatically, depending on the Dialect and actual driver you have chosen.
Enter your configuration information in this dialog. Details about the configuration options can be found in Hibernate Reference Documentation.
Press Finish to create the configuration file, after optionally creating a Console configuration, the hibernate.cfg.xml will be automatically opened in an editor. The last option Create Console Configuration is enabled by default and when enabled, it will automatically use the hibernate.cfg.xml for the basis of a Console configuration.
A Console configuration describes how the Hibernate plugin should configure Hibernate and what configuration files, including which classpath are needed to load the POJO's, JDBC drivers etc. It is required to make usage of query prototyping, reverse engineering and code generation. You can have multiple named console configurations. Normally you would just need one per project, but more is definitely possible if your project requires this.
You can create a console configuration by running the Console Configuration Wizard, shown in the following screenshot. The same wizard will also be used if you are coming from the hibernate.cfg.xml wizard and had enabled Create Console Configuration .
The wizard will look at the current selection in the IDE and try and auto-detect the settings which you then can just approve or modify to suit your needs.
The dialog consists of five tabs:
Main for the basic/required settings
The following table describes the available settings on the Main tab. The wizard can automatically detect the default values for most of them if you started the wizard with the relevant java project or resource selected.
Table 4.1. Hibernate Console Configuration Parameters
Parameter |
Description |
Auto detected value |
---|---|---|
Name |
The unique name of the console configuration |
Name of the selected project |
Type |
Choose between "Core", "Annotations" and "JPA". Note that the two latter requires running Eclipse IDE with a JDK 5 runtime, otherwise you will get classloading and/or version errors. |
No default value |
Project |
The name of a java project which classpath should be used in the console configuration |
Name of the selected project |
Database connection |
DTP provided connection that you can use instead of what is in cfg.xml and jpa persistence.xml. It's possible to use either already configured hibernate or JPA connection or specify a new one here. |
[Hibernate Configured connection] |
Property file |
Path to a hibernate.properties file |
First hibernate.properties file found in the selected project |
Configuration file |
Path to a hibernate.cfg.xml file |
First hibernate.cfg.xml file found in the selected project |
Persistence unit |
Name of the persistence unit to use |
No default value (let Hibernate Entity Manager find the persistence unit or it can be defined manually using Browse button) |
The two latter settings are usually not required if you specify a project and it has
/hibernate.cfg.xml
or
/META-INF/persistence.xml
in its project classpath.
Options for the additional/optional settings
The next table describes Hibernate Console Configuration options available on the Options tab.
Table 4.2. Hibernate Console Configuration Options
Parameter |
Description |
Auto detected value |
---|---|---|
Database dialect |
Define a database dialect. It's possible either to write your value or choose from list. |
No default value |
Naming strategy |
Fully qualified classname of a custom NamingStrategy. Only required if you use a special naming strategy. |
No default value |
Entity resolver |
Fully qualified classname of a custom EntityResolver. Only required if you have special xml entity includes in your mapping files. |
No default value |
Classpath for classpath
The following table specifies the parameters of the Classpath tab of the wizard.
Table 4.3. Hibernate Console Configuration Classpath
Parameter |
Description |
Auto detected value |
---|---|---|
Classpath |
The classpath for loading POJO and JDBC drivers; only needed if the default classpath of the Project does not contain the required classes. Do not add Hibernate core libraries or dependencies, they are already included. If you get ClassNotFound errors then check this list for possible missing or redundant directories/jars. |
Empty |
Include default classpath from project |
When enabled the project classpath will be appended to the classpath specified above |
Enabled |
Mappings for additional mappings
Parameters of the Mappings tab of the Hibernate Console Configuration wizard are explained below:
Table 4.4. Hibernate Console Configuration Mappings
Parameter |
Description |
Auto detected value |
---|---|---|
Mapping files |
List of additional mapping files that should be loaded. Note: A hibernate.cfg.xml or persistence.xml can also contain mappings. Thus if these are duplications here, you will get "Duplicate mapping" errors when using the console configuration. |
empty |
and the last tab Common
It allows to define general aspects of the launch configuration including storage location, console encoding and some others.
Clicking Finish creates the configuration and shows it in the Hibernate Configurations view.
When you created a hibernate console configuration you can modify it in 2 ways:
right-click on the configuration in Hibernate Configurations View->Edit Configuration or just double-click on Console Configuration item.
After clicking you will see the Edit Configuration Wizard that is similar to Create Console Configuration ,described in Creating a Hibernate Console Configuration section.
use Properties view for modifying some of Console Configuration properties.
The following table describes the available settings in the Properties view. Most properties are changeable by left click but some are not.
Table 4.5. Properties
Property |
Description |
Is Changeable |
---|---|---|
Additional mapping files |
List of additional mapping files that should be loaded. |
False |
Configuration file |
Path to a hibernate.cfg.xml file |
False |
Connection |
DTP provided connection that you can use instead of what is in cfg.xml and jpa persistence.xml. It's possible to use either already configured hibernate or JPA connection or specify a new one here. |
True |
Name |
The unique name of the console configuration |
True |
Project |
The name of a java project which classpath should be used in the console configuration |
True |
Properties file |
Path to a hibernate.properties file |
False |
Type |
Choose between "CORE", "ANNOTATIONS" and "JPA" according to the method of relational mapping you want to use. Note, the two latter requires running Eclipse IDE with a JDK 5 runtime, otherwise you will get classloading and/or version errors. |
True |
To close Hibernate Console Configuration you need do right-click your configuration and choose Close Configuration option
While closing configuration the connection with database will be closed, jar libs will be unlock (for Windows) and other resources will set as free.
A "click-and-generate" reverse engineering and code generation facility is available. This facility allows you to generate a range of artifacts based on database or an already existing Hibernate configuration, be that mapping files or annotated classes. Some of these are POJO Java source file, Hibernate .hbm.xml , hibernate.cfg.xml generation and schema documentation.
To start working with this process, start the Hibernate Code Generation which is available in the toolbar via the Hibernate icon or via the Run > Hibernate Code Generation menu item.
When you click on Open Hibernate Code Generation Dialog... the standard Eclipse launcher dialog will appear. In this dialog you can create, edit and delete named Hibernate code generation "launchers".
The first time you create a code generation launcher you should give it a meaningful name, otherwise the default prefix New_Generation will be used.
The "At least one exporter option must be selected" is just a warning stating that for this launch to work you need to select an exporter on the Exporter tab. When an exporter has been selected the warning will disappear.
The dialog also have the standard tabs Refresh and Common that can be used to configure which directories should be automatically refreshed and various general settings launchers, such as saving them in a project for sharing the launcher within a team.
On the Main tab you see the following fields:
Table 4.6. Code generation "Main" tab fields
Field |
Description |
---|---|
Console Configuration |
The name of the console configuration which should be used when code generating |
Output directory |
Path to a directory where all output will be written by default. It's possible to enter absolute directory path, for example - "d:/temp". Be aware that existing files will be overwritten, so be sure to specify the correct directory. |
Reverse engineer from JDBC Connection |
If enabled, the tools will reverse engineer the database available via the connection information in the selected Hibernate Console Configuration and generate code based on the database schema. If not enabled, the code generation will just be based on the mappings already specified in the Hibernate Console configuration. |
Package |
The package name here is used as the default package name for any entities found when reverse engineering |
reveng.xml |
Path to a reveng.xml file. A reveng.xml file allows you to control certain aspects of the reverse engineering. e.g. how jdbc types are mapped to hibernate types and especially important which tables are included/excluded from the process. Clicking "setup" allows you to select an existing reveng.xml file or create a new one. See more details about the reveng.xml file in Chapter 6, Controlling reverse engineering. |
reveng. strategy |
If reveng.xml does not provide enough customization you can provide your own implementation of an ReverseEngineeringStrategy. The class needs to be in the classpath of the Console Configuration, otherwise you will get class not found exceptions. See Section 6.3, “Custom strategy” for details and an example of a custom strategy. |
Generate basic typed composite ids |
A table that has a multi-column primary key a <composite-id> mapping
will always be created. If this option is enabled and there are matching
foreign-keys each key column is still considered a 'basic' scalar (string, long,
etc.) instead of a reference to an entity. If you disable this option a
|
Detect optimistic lock columns |
Automatically detect optimistic lock columns. Controllable via reveng. strategy; the current default is to use columns named VERSION or TIMESTAMP. |
Detect many-to-many tables |
Automatically detect many-to-many tables. Controllable via reveng. strategy. |
Detect one-to-one associations |
Reverse engineering detects one-to-one associations via primary key and both hbm.xml and annotation generation generates the proper code for it. The detection is enabled by default (except for Seam 1.2 and Seam 2.0) reverse engineering. For Hibernate Tools generation there is a checkbox to disable if not wanted. |
Use custom templates |
If enabled, the Template directory will be searched first when looking up the templates, allowing you to redefine how the individual templates process the hibernate mapping model. |
Template directory |
A path to a directory with custom templates |
The Exporters tab is used to specify which type of code that should be generated. Each selection represents an Exporter that is responsible for generating the code, hence the name.
The following table describes in short the various exporters. Remember you can add/remove any Exporters depending on your needs.
Table 4.7. Code generation "Exporter" tab fields
Field |
Description |
---|---|
Domain code |
Generates POJO's for all the persistent classes and components found in the given Hibernate configuration. |
DAO code |
Generates a set of DAO's for each entity found. |
Hibernate XML Mappings |
Generate mapping (hbm.xml) files for each entity. |
Hibernate XML Configuration |
Generate a hibernate.cfg.xml file. Used to keep the hibernate.cfg.xml update with any new found mapping files. |
Schema Documentation (.html) |
Generates a set of html pages that documents the database schema and some of the mappings. |
Generic Exporter (hbmtemplate) |
Fully customizable exporter which can be used to perform custom generation. |
Schema Export (.ddl) |
Generates the appropriate SQL DDL and allows you to store the result in a file or export it directly to the database. |
Each Exporter listens to certain properties and these can be setup in the Properties section where you can add/remove predefined or customer properties for each of the exporters. The following table lists the time of writing predefined properties:
Table 4.8. Exporter Properties
Name |
Description |
---|---|
jdk5 |
Generate Java 5 syntax |
ejb3 |
Generate EJB 3 annotations |
for_each |
Specifies for which type of model elements the exporter should create a file and run through the templates. Possible values are: entity, component, configuration |
template_path |
Custom template directory for this specific exporter. You can use Eclipse variables. |
template_name |
Name for template relative to the template path |
outputdir |
Custom output directory for this specific exporter. You can use Eclipse variables. |
file_pattern |
Pattern to use for the generated files, relatively for the output dir. Example: {package-name}/{class-name}.java . |
dot.executable |
Executable to run GraphViz (only relevant, but optional for Schema documentation) |
drop |
Output will contain drop statements for the tables, indices and constraints |
delimiter |
If specified the statements will be dumped to this file |
create |
Output will contain create statements for the tables, indices and constraints |
scriptToConsole |
The script will be output to Console |
exportToDatabase |
Executes the generated statements against the database |
outputFileName |
If specified the statements will be dumped to this file |
haltOnError |
Halts the build process if an error occurs |
format |
Applies basic formatting to the statements |
schemaUpdate |
Updates a schema |
To add a property to the chosen Exporter click the Add button in the Properties section. In the appeared dialog you should select the property from the proposed list and the value for it.
If the property is a directory, it is possible to browse directories in the Value field.
The Hibernate Mapping File editor provides XML editing functionality for the hbm.xml and cfg.xml files. The editor is based on the Eclipse WTP tools and extends its functionality to provide Hibernate specific code completion.
Package, class, and field completion is enabled for relevant XML attributes. The
auto-completion detects its context and limits the completion for e.g.
<property>
and only shows the properties/fields available in the
enclosing <class>
, <subclass>
etc. It is also
possible to navigate from the
hbm.xml
files to the relevant class/field in java code.
This is done via the standard hyperlink navigation functionality in Eclipse; per default it is done by pressing F3 while the cursor is on a class/field or by pressing Ctrl and the mouse button to perform the same navigation.
For java completion and navigation to work the file needs to reside inside an Eclipse Java project, otherwise no completion will occur.
Java completion does not require a Hibernate console configuration to be used.
Table and column completion is also available for all table and column attributes.
Table/Column completion requires a proper configured hibernate console configuration and this configuration should be the default for the project where the hbm.xml resides.
You can check which console configuration is selected under the Properties of a project and look under the Hibernate Settings page. When a proper configuration is selected it will be used to fetch the table/column names in the background.
Currently it is not recommended to use this feature on large databases since it does not fetch the information iteratively. It will be improved in future versions.
The structured editor represents the file in the tree form. It also allows to modify the structure of the file and its elements with the help of tables provided on the right-hand area.
To open any mapping file in the editor, choose Open With > Hibernate 3.0 XML Editor option from the context menu of the file. The editor should look as follows:
For the configuration file you should choose Open With > Hibernate Configuration 3.0 XML Editor option.
The editor is meant for editing .properties
files. It contains two
tabs: the Properties (UI) tab and the Source tab for
manual editing.
For hibernate.properties
file JBoss Tools Properties
Editor provides content assist which is available both for hibernate properties
and property values. You can make use of the content assist while editing the file in the
Source view and in the Properties view of the editor.
To add the property in the Properties view, click the Add button.
In the Name field press Ctrl+Space to invoke the content assist. It will suggest 'hibernate.' which is the prefix for all hibernate properties. After selecting 'hibernate.' and invoking the content assist again, other prefixes and properties are displayed as the proposals with a description of each one.
When invoking the content assist in the Value field, it also provides a list of proposals.
In the Source view of the editor, content assist also could be invoked both for properties names and values:
A reveng.xml file is used to customize and control how reverse engineering is performed by the tools. The plugins provide an editor to ease the editing of this file and hence used to configure the reverse engineering process.
The editor is intended to allow easy definition of type mappings, table include/excludes and specific override settings for columns, e.g. define an explicit name for a column when the default naming rules are not applicable.
Not all the features of the .reveng.xml file are exposed or fully implemented in the editor, but the main functionality is there. To understand the full flexibility of the reveng.xml , please see Section 6.2, “hibernate.reveng.xml file”
The editor is activated as soon as an .reveng.xml file is opened. To get an initial reveng.xml file the Reverse Engineering File Wizard can be started via Ctrl+N and Hibernate > Hibernate Reverse Engineering File (reveng.xml) then.
Or you can get it via the Code Generation Launcher by checking the proper section in the Main tab of the Hibernate Code Generation Wizard.
The following screenshot shows the Overview page where the wanted console configuration is selected (auto-detected if Hibernate 3 support is enabled for the project)
The Table Filter page allows you to specify which tables to include and exclude. Pressing Refresh shows the tables from the database that have not yet been excluded.
The Type Mappings page is used for specifying type mappings from JBDC types to any Hibernate type (including usertypes) if the default rules are not applicable. Here again to see the database tables press Refresh button underneath. More about type mappings you can find further in the Type Mappings section.
The Table and Columns page allows you to explicit set e.g. which hibernatetype and propertyname that should be used in the reverse engineered model. For more details on how to configure the tables while reverse engineering read the Specific table configuration section.
Now that you have configured all necessary parts, you can learn how to work with Hibernate Console Perspective.
The Hibernate Console Perspective combines a set of views which allow you to see the structure of your mapped entities/classes, edit HQL queries, execute the queries, and see the results. To use this perspective you need to create a Console configuration.
To view your new configuration and entity/class structure, switch to Hibernate Configurations View. Expanding the tree allows you to browse the class/entity structure and see the relationships.
The Console Configuration does not dynamically adjust to changes done in mappings and java code. To reload the configuration select the configuration and click the Reload button in the view toolbar or in the context menu.
Besides, it's possible to open source and mapping files for objects showed in Hibernate Configurations View. Just bring up the context menu for a necessary object and select Open Source File to see appropriate Java class or Open Mapping File to open a proper .hbm.xml.
In order to get a visual feel on how entities are related as well as view their structures, a Mapping Diagram is provided. It is available by right clicking on the entity you want a mapping diagram for and then choosing Mapping Diagram.
To make Mapping Diagram usage easier you can use Rules, Grid,Snap to Geometry checkboxes in the View menu.
If you will select Rules checkbox, the view print page scale will be added to the page. The numbers on the scale show its size in inches.If you click on the scale a Ruler Guide will appear on the diagram. You can connect any diagram item to it.To connect the items you should move their tops to the Ruler Guide. And while moving the ruler guide, the items will be moved together with it as a whole.
If you'll select Grid checkbox, the grid will appear on the diagram.
The checkbox Snap to Geometry helps to put the items of the diagram into allineation with the grid.
For better navigating through the diagram use Outline view which is available in the structural and graphical modes.
To switch over between the modes use the buttons in the top-right corner of the Outline view.
The options in the context menu of the mapping diagram are listed in the next table.
Table 4.9. Context Menu Options of the Mapping Diagram
Icon |
Command |
Description |
---|---|---|
|
Show|Hide connections | Allows to select what types of connections should be shown on the diagram:
|
Select All |
Makes all the diagram elements selected | |
|
Auto layout |
Used to dispose all the items of the diagram in a standard manner |
|
Export as Image |
Allows to export a diagram as .png , .jpeg or .bmp |
When you open the context menu while clicking an item on the diagram, it quite differs from the one described before.
The next table describes all the extra options in the menu of mapping items:
Table 4.10. Extra Options in the Context Menu of Mapping Item
Icon |
Command |
Description |
---|---|---|
|
Open Source File |
Makes it possible to open a source file for a chosen object/element. The selected element will be highlighted in the open file. |
|
Open Mapping File |
Makes it possible to open a mapping file for a chosen object/element. The selected element will be highlighted in the open file. |
|
Show|Hide shape(s) |
Used to hide/show an item on the mapping diagram |
|
Expand|Collapse shape(s) |
Used for expanding/collapsing fields of the item |
All the described types of the context menu are also available in the Outline view.
The below table lists the actions that could be performed using the keyboard keys (or keys combinations).
Table 4.11. Hibernate Mapping Diagram Shortcut Keys
Command |
Binding |
---|---|
Scroll the diagram content |
Ctrl + Shift + arrows |
Collapse/Expand selected item(s) |
Enter |
Show/Hide selected item(s) |
+ |
Sort items in alphabetical order or return the initial state |
Space |
Navigate between the items |
Arrows |
It's possible to save the diagram in the eclipse workspace. Click the usual
File > Save As
option, the wizard will ask you to set the location within you project where
to save the file and give the name for the diagram. The item's names concatenated
with the ampersand symbols are set as the default name for a diagram. The file is saved
with the .hibernate
extension.
If you restart the Eclipse with the mapping diagram opened, the mapping diagram will be restored with the message like on the figure below. To view the diagram content, you should perform the refreshing.
There are some useful commands in the toolbar.
They are described in the table below.
Table 4.12. Command in Diagram View Toolbar
Icon |
Command |
Description |
---|---|---|
|
Refresh Visual Mapping |
It update Mapping Diagram if Console Configuration was changed. |
|
Zoom Box |
Used to define scale of the diagram. Also it's used for Mapping Diagram printing. If you want to put the whole diagram to one print page, you need select Page option in the Zoom Box. |
|
Auto layout |
Used to arrange all diagram items in a standard manner. |
|
Show|Hide connections |
Used to show or hide connection on the diagram. Moreover you can choose what type of connections must be present on the diagram (Property Mappings, Class Mappings, Associations or Foreign key constraints) . |
|
Expand|Collapse |
Used for expanding/collapsing fields of the item. |
|
Show|Hide shape(s) |
Used to hide/show an item on the mapping diagram. |
Queries can be prototyped by entering them into the HQL or Criteria Editor. To execute a query you should click the green run button in the editor toolbar or press Ctrl+Enter .
To open the query editors right-click your project Console Configuration and select HQL Editor (or Hibernate Criteria Editor).
If the context menu items are disabled then you need at first to create a Session Factory. That is done by simply expanding the Session Factory node.
When open the editors they should automatically detect the chosen Console Configuration.
To get a prefill query for any entity (or any entity child node) listed in the Session Factory you should double-click it. This will open the HQL Editor with the associated query.
Choosing HQL Editor in the context menu for any entity (or any entity child node) will also open the HQL editor with the associated query. If you choose Hibernate Criteria Editor in the context menu, it will open Hibernate Criteria Editor with the associated criteria.
It's also possible to copy a portion of code from .java file into the HQL or Criteria editor. To do this make use of the Quick Fix option ( Ctrl + 1).
You can also update the original java code according to changes in the HQL or Criteria editor. For that you should save your HQL/Criteria query and submit the replacing in appeared confirmation dialog.
Also you can pin HQL editor and Criteria
editor for one tab in Hibernate Query Result view. For
that you need click on Stick result to one tab
button( ). In the issue query executions results will be shown in one tab (no
more will be opened).
Moreover you are able to rename tab in Hibernate Query Result. Click the tab, and type a new name in Property View->Tab name field.
Errors during creation of the Session Factory or running the queries (e.g. if your configuration or query is incorrect) will be shown in a message dialog or inclined in the view that detected the error, you may get more information about the error in the Error Log View on the right pane.
Results of a query will be shown in the Hibernate Query Result View and details of possible errors (syntax errors, database errors, etc.) can be seen in the Error Log View.
HQL queries are executed by default using list()
thus without any
limit of the size of the output the query could return a large result set. You might run
out of memory. To avoid this you can put a value in the Max results field to reduce the
number of elements returned.
If the Hibernate Dynamic Query Translator View is visible while writing in the HQL Editor it will show the generated SQL for a HQL query.
The translation is done each time you stop typing into the editor, if there are errors in the HQL the parse exception will be shown embedded in the view.
As you can see on the figure,when clicking on class/entity Properties view shows the number of query results as well as the time of executing.
It also displays the structure of any persistent object selected in the Hibernate Query Results View. Editing is not yet supported.
You can also use Properties view when clicking on the configuration itself in Hibernate Configuration View( Modifying a Hibernate Console Configuration section).
Using this wizard you can add the next Hibernate annotations to the class: @Column , @Entity , @ManyToOne , @OneToMany , @OneToOne , @ManyToMany , @MappedSuperclass , @Id , @GeneratedValue , @Version
@Column is added to all String properties.
@Entity is always declared before any class where it doesn't present.
@ManyToOne , @OneToMany , @OneToOne , @ManyToMany - this annotations are declared according to the classes hierarchy.
@MappedSuperclass is added to abstract superclasses.
@Id , @GeneratedValue are added automatically only to the properties under the name "Id",where they don't present.
@Version is declared in case you select Enable optimistic locking.
This section doesn't cover the meaning of the Hibernate annotations , for more information read Hibernate Annotations Documentation .
To open this wizard you should right click the class you want to enrich with annotations >Source>Generate Hibernate/JPA annotations . You will see the Hibernate:add JPA annotations dialog.
In the top of it you can see the list of all classes that will be passed through refactoring. Besides the class you have selected in this list you can also find its superclasses and the classes that objects present in the current class as properties. If you want to add new classes or package to the list of classes, you should click the Back button. In result you will see Add classes and packages page.
Here you can add one more classes or whole package, moreover you can limit dependencies depth by selecting depth control option (more about this option you will find in Creating a Hibernate Mapping File). When finished just press the Next button and you will be returned to The following classes will be changed page and will be able to continue work with it.
By default the tags are added to the fields of selected classes. But you can change this option to Getters in Preferred location of Annotations dropdownlist and then all the annotations will be added to the getter methods. If you choose Auto select from class preference then the annotations are added according to the majority of the already existed ones positions.
If it's nessecary to map your String properties to the columns that length differ from
the default value(255) ,change
Default string length field
and @Column(length = your length)
will be created before every String
property.
You can add optimistic locking capability to an entity bean by selecting Enable optimistic locking checkbox. This operation will add version property to all the selected classes. The property will be also annotated with @Version ,getter and setter will be created. If the property is already exists,it won't be created ,but the getters,setters will be generated. If there is already @MappedSuperclass with version in the base class of the current class - "version" is not inserted into the current class.
After defining all necessary settings in the current step press Next and follow the next wizard steps.
The view represents two windows: one with the source code and and the second with
refactored one. With the help of ,
,
,
buttons you can quickly navigate between the differences in the code. If
you don't agree with some changes you can't undo them but you can remove the class from the
list of classes that need refactoring.
To apply the changes click Finish .
It is possible to configure the eclipse plugin to route all logging made by the plugins and hibernate code it self to the Error Log View in Eclipse.
Error Log View is very useful tool to solve any problem which appears in Hibernate Tools Plugins. You can use if there are troubles with setting up Hibernate Console Configuration.
This is done by editing the hibernate-log4j.properties in org.hibernate.eclipse/ directory/jar . This file includes a default configuration that only logs WARN and above to a set of custom appenders (PluginFileAppender and PluginLogAppender). You can change these settings to be as verbose or silent as you please - see Hibernate Documentation for interesting categories and Log4j documentation.
Find more on how to configure logging via a log4j property file in Log4j documentation.
Starting from 3.0.0 Alpha1 version of JBoss Tools Hibernate plugins support Eclipse Dali integration what now makes it possible to use a Hibernate as a complete JPA development platform.
When starting a new JPA project from New > Other > JPA > JPA Project (or simply New > JPA Project in JPA Perspective), the first wizard page looks as follows.
It's possible here to select a target runtime and change the project configuration, or you can leave everything as it is.
On the JPA Facet page you should choose Hibernate as a target platform. Also select the proper database connection, if it is defined, or add a new one by clicking the Add connection link.
Hitting Finish will generate the project.
Please note, if you choose Hibernate as a platform while creating a JPA/Dali project, a Hibernate Console Configuration for the project is created automatically when the wizard finishes its work. It allows a full usage of Hibernate Tools features without additional setup.
By enabling Hibernate platform specific features you can now generate DDL and Entities. For that find JPA Tools > Generate Tables from Entities/Generate Entities from Tables options in the context menu of your JPA project.
Please, remember to put the proper database driver to the classpath of your project.
The Generate Entities wizard first will ask you to choose the directory where all output will be written.
To generate entities you can use:
a Hibernate Console Configuration (proposed by default)
Just make sure that the Use Console Configuration checkbox is selected and choose a needed configuration from the Console configurations list box.
or a DTP connection directly
Just uncheck Use Console Configuration and adjust database settings.
All the same you do with Generate Entities Wizard you can do with Generate DDL wizard. Special feature for Generate DDL wizard is possible automatic execution of Generation DDL in the database.
Thus, you can now have the Hibernate runtime support in Eclipse JPA projects.
Also Hibernate Annotations are supported in Dali Java Persistence Tools. The next annotations are integrated with JPA Details view:
Id Generator annotations - @GenericGenerator and @GeneratedValue
Property annotations- @DiscriminatorFormula, @Generated Annotation, @Index annotation
Mapping Queries annotations - @NamedQuery and @NamedNativeQuery
More information about Hibernate Annotation you can find in Hibernate Annotations Reference Guide.
There is full information about native Dali plugin features on Eclipse Documentation page.