Mostrando entradas con la etiqueta maven. Mostrar todas las entradas
Mostrando entradas con la etiqueta maven. Mostrar todas las entradas

miércoles, 6 de abril de 2016

Uso de maven en proyecto java

Maven is a framework, or an application if you may, which helps you manage a project’s lifecycle. For those new to Maven, usually we have our IDE such as EclipseNetBeans or SpringSource Tool Suite (STS), to handle the creation, compilation and deploying of projects. Instead, we can use Maven independent from the development environment (to some extent), to manage the project’s lifecycle. In this article we will see how Maven can help use in managing dependencies and creating a final product which can be deployed to a production system.
All code listed below is available at: http://code.google.com/p/java-creed-examples/source/checkout, under the maven project. Most of the examples will not contain the whole code and may omit fragments which are not relevant to the example being discussed. The readers can download or view all code from the above link.
This article focuses on how we can use Maven together with STS to manage our simple project. We will introduce what Maven can do and how can it be configured to aid us in our work. Here we will not show all Maven features, but focus only on those required to manage a standalone Java application.

Introduction to Maven

Maven is famous for its dependency management. What is that? In our projects we make use of third party JARs such as JUnit to name one. What do we usually do to use a third party JAR file or a group of JARs? We go on the Internet and look for it. We then download it and all of its dependencies. Note that a JAR may depend on another and we need to resolve all dependencies as otherwise our code may not compile. With Maven, it is all a different story. All we need is to go into the Maven Repository (a place where third party JARs can be downloaded from). Then we find our JAR and add it to the pom.xml file (will see later on). Maven will download this JAR and all its dependencies and adds them to the classpath for us.
But Maven is more than this. With Maven we can create projects with a predefined structure, test our code, and install/deploy it to name a few. One must note that Maven is a framework where new things (technically referred to as plugins) can be added. Therefore, one can program Maven to take care of other things that the standards features named before.
This article is more about how to use Maven to manage a Java application. The description is kept to a minimum in order not to end up with a too long and unfocused article.

Setting up the Project

Let say that we want to have an application that adds to inputs, say a and b, and prints the results as shown in the following figure.
Calculator Application
Calculator Application
This application is very trivial but it has all the prerequisites required to show most of the important Maven features when dealing with a Java standalone application. In this article we will do the following
  1. Start using Maven with an existing project
  2. Add all required dependencies
  3. Test our program
  4. Deploy our program, together with its dependencies
  5. Work with JAR files not available in a Maven repository
Before we hit to the road, let us have a look at the application without Maven. The following figure lists all classes and resources (such as the log4j.properties).
Project Structure
Project Structure
This is not a typical Maven folder structure, but we did this on purpose. We want to adopt Maven to an existing project and will keep the structure as is. One must note that the structure is irrelevant and once configure properly, it will work.
Here we have four source folders:
  1. src: where we have all our code
  2. resources: where we have configuration files such as the logging configuration
  3. test-src: where we have all our test classes
  4. test-resources: where we have the configuration to be used when testing. Note that we may need finer logging when testing, while in production we want to have a higher logging level not to impact the application performance.
To be fair, Maven organises the folders in a very similar way and unless forced to do otherwise, it is always recommended to follow Maven’s convention. We took this path to show the reader how Maven can be also adopted with an existing project with minimal refactoring.
It is now time to start working with Maven.

Make it a Maven Project

The first this one should do, if he/she would like to work with Maven within STS is to make a project as a Maven Project. I said: “would like to work with Maven within STS “, you can use Maven as a command prompt tool once you install it and modify the system path to find the mvn command. But this article is all about STS and Maven so we will restrict ourselves talking about these two, with one exception at the end, when we work with a third party JAR not available in the Maven repository.
STS 3.x allows the user to install Maven during the installation process. If your STS version does not have the Maven plugin installed, than it is recommend doing so before proceeding. Basically this is the m2eclipse Eclipse plugin and more information about this is found here.
In order to make a project a Maven Project all needs doing is to right-click on the project and select Configure and then select Convert to Maven Project. This will open the following dialog from where we can enter the basic, but required, information.
Create new POM
Create new POM
The Group Id is the company wide name. This is usually the company’s domain name. The Artifact Id is the project name. This uniquely identifies the project within the company. The Version describes the current version of the project and the Packaging is how we will deploy. All this can be modified at a later stage but Maven requires these before it can start. This will generate a Project Object Model (pom) file: pom.xml, as shown next.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacreed.examples</groupId>
  <artifactId>maven-examples</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
We need to modify this, as for a start, we do not have all source folder added to the pom. This is very important as otherwise Maven will not pick the content of these source folders.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacreed.examples</groupId>
  <artifactId>maven-examples</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>resources</directory>
      </resource>
    </resources>
    <testSourceDirectory>test-src</testSourceDirectory>
    <testResources>
      <testResource>
        <directory>test-resources</directory>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
Here we added the resources used when in production and the test classes and resources. The next step would be: manage the dependencies through Maven, as described next.

Observation

When editing the pom.xml, you may encounter the following problem:
Project configuration is not up-to-date with pom.xml. Run Maven->Update Project or use Quick Fix.
Simply, right click on the project and select Maven from the menu. Then select Update Project and follow the instructions. This is quite common and you may have to do it several times, especially when modifying the pom file.

Manage Dependencies with Maven

Assuming that the dependencies are only managed through Maven, the project will not compile. Our projects makes use of SLF4J for logging and JUnit for testing. We can add these by modifying the pom file as showed next.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacreed.examples</groupId>
  <artifactId>maven-examples</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>resources</directory>
      </resource>
    </resources>
    <testSourceDirectory>test-src</testSourceDirectory>
    <testResources>
      <testResource>
        <directory>test-resources</directory>
      </testResource>
    </testResources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.2</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.2</version>
    </dependency>
  </dependencies>
</project>
Here we just added three dependencies. These can all be found at: http://mvnrepository.com. Here we can search for most of the JARs (or as referred to by Maven: dependencies). One must note that we can search in other repositories, such as: http://ebr.springsource.com/repository/app/. But before we can use this repository (or any other repository), we must add the repository location to the pom file. We do not require to do this for our project as all of our dependencies can be found at http://mvnrepository.com. For completeness, the following lists shows what has to be added to the pom file (as described in here).
  • The bundle repository:
      <repository>
        <id>com.springsource.repository.bundles.release</id>
        <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
        <url>http://repository.springsource.com/maven/bundles/release</url>
      </repository>
    
      <repository>
        <id>com.springsource.repository.bundles.external</id>
        <name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
        <url>http://repository.springsource.com/maven/bundles/external</url>
      </repository>
  • The library repository:
      <repository>
        <id>com.springsource.repository.libraries.release</id>
        <name>SpringSource Enterprise Bundle Repository - SpringSource Library Releases</name>
        <url>http://repository.springsource.com/maven/libraries/release</url>
      </repository>
    
      <repository>
        <id>com.springsource.repository.libraries.external</id>
        <name>SpringSource Enterprise Bundle Repository - External Library Releases</name>
        <url>http://repository.springsource.com/maven/libraries/external</url>
      </repository>
Please note that the above is not part of our example, and was added here to show than more repositories can be added.
It is also good to note that one of the dependencies has a scope, which is set to test>. This means that this dependency is only required for testing and it is not required for runtime. Only the classes under the test source folder make reference to this dependency. Why do we need to mark such dependencies? This plays a role when Maven managed our dependencies in deployment phase. In this phase Maven will ignore these dependencies, together with any classes under the test source folder and test resrouces.
Once Maven if finished to do its magic you will notice that a new library, called: Maven Dependencies, is added. Here we will find all dependencies added through Maven as shown next.
Maven Dependencies
Maven Dependencies

Observation

Note that the above figure shows five JARs when we only added three dependencies. This is because Maven has resolved the indirect dependencies (the dependencies of our dependencies and their dependencies too) automatically for us and added these to the project classpath.
When we add or remove dependencies, Maven downloads them in to our local PC (or as it is technically referred to: Local Meven Repository) for us and updates this library. It is important to manage all of our dependencies from Maven. Unfortunately this is not always the case especially with new releases of some dependencies. Furthermore, while Maven is very popular in managing dependencies, some JARs are not found in any repository and we need to work around that as we will see later on.
The project now compiles as it has all that it requires. We can run the project from STS through the Main class and works well. Now let us see how to use Maven to manage the other parts of the project lifecycle.

Building the project with Maven

So far we only used the Maven ability to manage our dependencies, which is pretty cool. It alone is already worth giving Maven a try. All projects in this website that require dependencies are managed through Maven. Like that when someone downloads the examples, he or she does not have to worry about the dependencies as Maven will handle that.
If you right-click on the pom.xml file and select Run As menu, you will see a list of options as shown in the following figure.
Maven run as menu options
Maven run as menu options
If you select the Maven install option, Maven will compile and test our code and if all goes well it creates the JAR file in the target directory. The Maven clean option will empty the target directory and the Maven test will simply run the test cases.

Observation

When using a command for the first time, Maven downloads several things. When we originally installed Maven, Maven only installed the bare minimum. Anything required is downloaded and installed on the fly.
It looks like we have everything we need and the JAR file was compiled, tested and deployed through Maven. But if we try to run the JAR file (by double clicking on it) nothing will happen. If we try to execute it from the command prompt we will get the following error.
C:\javacreed\maven\target>java -jar maven-examples-0.0.1-SNAPSHOT.jar
no main manifest attribute, in maven-examples-0.0.1-SNAPSHOT.jar
What did we miss? So far we modified the pom to be able to compile and test and these phases work well. The pom is not ready to deploy our application properly, as we will see in the next section.

Add main class to pom

One of Maven’s strengths is deployment. Through the pom file we can instruct Maven about how to deploy our project, such as which class is the main class as we will see in this section. This can be achieved by simply adding the following to the pom.
Do not rush adding this to the pom file, as it is not complete and it still missing the dependencies.
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <configuration>
    <archive>
      <manifest>
        <mainClass>com.javacreed.maven.examples.Main</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>
Here we are telling Maven to modify the MANIFEST.MF file, which was too generated by Maven as shown next. Maven will generate the following manifest including the Main-Class as highlighted in the following example.
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: Albert
Build-Jdk: 1.7.0_02
Main-Class: com.javacreed.maven.examples.Main
We are far from ready as so far we instructed Maven to simply add the main class to the manifest. We need to also modify the manifest to include our dependencies. As is, our project will fail to run as the dependencies are not available at runtime as shown next.
C:\javacreed\maven\target>java -jar maven-examples-0.0.1-SNAPSHOT.jar
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
        at com.javacreed.maven.examples.CalculatorImpl.(CalculatorImpl.java:8)
        at com.javacreed.maven.examples.CalculatorFrame.(CalculatorFrame.java:15)
        at com.javacreed.maven.examples.Main$1.run(Main.java:12)
        at java.awt.event.InvocationEvent.dispatch(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$000(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 17 more
We have to also include the dependencies as we will see in the following section. So far we simply told Maven to add the selected class as the projects main class.

Add Runtime Dependencies

We have two ways to add the dependencies to the generated JAR file. We can either package everything as one JAR, having all dependencies extracted and re-packages with the generated JAR. Alternatively, we can have our dependencies copied to a folder relative to the JAR and modify the manifest accordingly. I prefer the second option but we will see how to do them both.
  • Everything packaged into one JAR
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <mainClass>com.javacreed.maven.examples.Main</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
      <executions>
        <execution>
          <id>make-my-jar-with-dependencies</id>
          <phase>package</phase>
          <goals>
            <goal>single</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  • Copied into a library folder
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <executions>
        <execution>
          <id>copy-dependencies</id>
          <phase>prepare-package</phase>
          <goals>
            <goal>copy-dependencies</goal>
          </goals>
          <configuration>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
            <overWriteReleases>false</overWriteReleases>
            <overWriteSnapshots>false</overWriteSnapshots>
            <overWriteIfNewer>true</overWriteIfNewer>
          </configuration>
        </execution>
      </executions>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>com.javacreed.maven.examples.Main</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
Here we are instructing Maven how to deploy our application and its dependencies. Note that in the second example we have two plugins and not one.

Observation

The second example may cause a known issue with m2eclipse plugin. All you need is to include the following to the pom.
<pluginManagement>
  <plugins>
    <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
    <plugin>
      <groupId>org.eclipse.m2e</groupId>
      <artifactId>lifecycle-mapping</artifactId>
      <version>1.0.0</version>
      <configuration>
        <lifecycleMappingMetadata>
          <pluginExecutions>
            <pluginExecution>
              <pluginExecutionFilter>
                <groupId>
                  org.apache.maven.plugins
                </groupId>
                <artifactId>
                  maven-dependency-plugin
                </artifactId>
                <versionRange>
                  [2.1,)
                </versionRange>
                <goals>
                  <goal>
                    copy-dependencies
                  </goal>
                </goals>
              </pluginExecutionFilter>
              <action>
                <ignore></ignore>
              </action>
            </pluginExecution>
          </pluginExecutions>
        </lifecycleMappingMetadata>
      </configuration>
    </plugin>
  </plugins>
</pluginManagement>
When we run Maven Install, Maven will produce our JAR file and copy the libraries to the folder lib as described in the pom file. Maven will update the manifest as shown next.
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: Albert
Build-Jdk: 1.7.0_02
Main-Class: com.javacreed.maven.examples.Main
Class-Path: lib/slf4j-api-1.7.2.jar lib/slf4j-log4j12-1.7.2.jar lib/lo
 g4j-1.2.17.jar
Here we are telling Java to add the following three JAR files, which are primarily used for logging. Note that the JUnit JAR files are not added to the manifest. That is because, JUnit is only used for testing and Maven will not deploy the testing classes and resources as indicated by its scope.
So far we saw how to manage the dependencies that were added to Maven. But what if we need to include a JAR file which is not found in Maven repository? In the following and final section we will see how to work with a custom, non-Maven managed, dependency.

Include non-Maven Dependencies

The simplest way to work with non-Maven dependencies is to add the new JAR file to the local Maven repository. Maven has a local repository which caches all downloaded dependencies. It first looks here and if not found in the Maven local repository, will look into the repositories located on the Internet and those defined in the pom.
The following steps illustrate how to do this.
  1. First obtain the JAR file. In this example we are using a simple JAR file called xTools.jar. Note that if this JAR depends on other JARs, then all these JARs need to be added to local Maven repository.
  2. Install the JAR file into the local Maven repository using the following command
    mvn install:install-file -Dfile=xtool.jar -DgroupId=com.javacreed.examples -DartifactId=xtool -Dversion=1.0.0 -Dpackaging=jar
    The parameters are self-explanatory. The above command will produce something like the following.
    C:\javacreed\lib>mvn install:install-file -Dfile=xtool.jar -DgroupId=com.javacreed.examples -DartifactId=xtool -Dversion=1.0.0 -Dpackaging=jar
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'install'.
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Maven Default Project
    [INFO]    task-segment: [install:install-file] (aggregator-style)
    [INFO] ------------------------------------------------------------------------
    [INFO] [install:install-file {execution: default-cli}]
    [INFO] Installing C:\javacreed\lib\xtool.jar to C:\javacreed\.m2\repository\com\javacreed\examples\xtool\1.0.0\xtool-1.0.0.jar
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 3 seconds
    [INFO] Finished at: Fri Jan 18 09:36:11 CET 2013
    [INFO] Final Memory: 3M/122M
    [INFO] ------------------------------------------------------------------------
  3. With the JAR within our local Maven repository, all we need to do is add the dependency to the pom, as we did with the others.
    <dependency>
      <groupId>com.javacreed.examples</groupId>
      <artifactId>xtool</artifactId>
      <version>1.0.0</version>
    </dependency>
This new dependency is treated like the others. When deploying our application, Maven will deploy it with the rest.
This concludes our article about how to use Maven with a standalone Java application. In this article we used a very simple Java application to demonstrate how to manage the dependencies with Maven and how to deploy our application together with its dependencies. Finally we saw how to use custom JAR which is not found in a Maven repository.

Funete:
http://www.javacreed.com/how-to-use-maven-with-an-application/

domingo, 6 de marzo de 2016

Crear una aplicación Maven Swing usando Hibernate - NetBeans IDE Tutorial

In this tutorial, you use the NetBeans IDE to create a Java Swing application from a Maven archetype. The application uses the Hibernate framework as the persistence layer to retrieve POJOs (plain old Java objects) from a relational database. The tutorial demonstrates how wizards in the IDE can help you create the necessary Hibernate files and add Hibernate dependencies to the POM. After creating the Java objects and configuring the application to use Hibernate, you create a GUI interface for searching and displaying the data.
Support for Maven is fully integrated in NetBeans IDE and Maven 3 is bundled with the IDE. You can create applications from the bundled Maven archetypes or from archetypes in remote repositories in the New Project wizard. The Maven Repository Browser enables you to explore your local and remote Maven repositories, examine artifacts and add project dependencies to the project's POM.
To build this application using Ant, see Using Hibernate in a Java Swing Application.
To build a Maven Java EE application, see Creating an Enterprise Application Using Maven.
Contents
Content on this page applies to NetBeans IDE 7.2, 7.3, 7.4 and 8.0
To follow this tutorial, you need the following software and resources.
Software or ResourceVersion Required
NetBeans IDE7.2, 7.3, 7.4, 8.0, Java bundle
Java Development Kit (JDK)version 7 or 8
Mavenversion 2.09 or newer
MySQL database serverversion 5.x
Sakila Databaseplugin available from update center
Before starting this tutorial you may want to familiarize yourself with the following documentation.

Creating the Database

This tutorial uses a MySQL database called sakila. The sample database is not included when you install the IDE so you need to first create the database to follow this tutorial.
The sakila database is a free sample MySQL database that is available from the MySQL site. To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin you can create the sakila database from the Services window. The sakila database is added to the list of databases in the Create MySQL database dialog box.
For more information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database tutorial.
  1. Open the Plugins manager and install the Sakila Sample Database plugin.
  2. After installing the plugin, start the MySQL database server by expanding the Databases node in the Services window, right-clicking the MySQL Server node and choosing Start.
  3. Right-click the MySQL Server node and choose Create Database.
  4. Select the Sakila database from the New Database Name drop down list in the Create MySQL Database dialog box. Click OK.
    Screenshot of Create MySQL Database dialog
    When you click OK the IDE will run a script to create the Sakila database and populate the database tables. You can see the results of running the script in the Output window. A node for the Sakila database is also added under the MySQL Server node.
  5. Right-click the Sakila node and choose Connect.
When you click Connect, a database connection node for the Sakila database (jdbc:mysql://localhost:3306/sakila [username on Default]) is listed under the Databases node. When a connection is open you can view the data in the database by expanding the connection node.

Configuring Maven

Maven is bundled with the IDE and installed when you install the IDE, but if this is your first Maven project you will want to check the Maven configuration settings in the Options window.
  1. Open the Options window in the IDE (Tools > Options; NetBeans > Preferences on Mac).
  2. Select the Java category in the Options window and click the Maven tab.
  3. Confirm that a Maven Home is specified.
    You can use the Maven version bundled with the IDE or specify the location of a local Maven installation (requires 2.0.9 or newer).
  4. Click OK to close the Options window.
Notes.
  • Maven support is automatically enabled when Java is enabled in the IDE. You will need to enable the Java EE plugin if it is not enabled.
  • In NetBeans IDE 7.1 and earlier versions of the IDE, the Maven tab in the Options window is located in the Miscellaneous category.

Viewing the Maven Repositories

The artifacts that are used by Maven to build all your projects are stored in your local Maven repository. When an artifact is declared as a project dependency, the artifact is downloaded to your local repository from one of the registered remote repositories.
Several well-known indexed Maven repositories are registered and listed in the repository browser by default. The registered repositories contain most of the public artifacts necessary for you to build your project. In most cases, you do not need to register any additional repositories unless your project requires artifacts found only in a private repository.
You can explore your local and remote Maven repositories and perform an immediate check for updates in the Services window. Any artifact that is in your local or remote repositories can be added as a project dependency. You can expand the Local repository node in the Services window to see the artifacts that are present locally. The artifacts listed under the remote repository nodes can be added as project dependencies, but not all of them are present locally. They are only added to the Local repository when they are declared as project dependencies.
To browse and update the Maven repositories perform the following steps.
  1. Choose Window > Services to open the Services window.
  2. Expand the Maven Repositories node in the Services window to view the repositories.
  3. Expand a repository node to view the artifacts.
  4. Right-click a repository node and choose Update Index in the popup menu to update the repository.
Screenshot of Maven Repositories in Services window
When your cursor is over an artifact, the IDE displays a tooltip with the artifact's coordinates. You can double-click an artifact's JAR file to view additional details about the artifact.
You can search for an artifact by right-clicking the Maven Repositories node in the Services window and choosing Find.
For more about managing Maven classpath dependencies and working with Maven repositories in the IDE, see the Dependency Management section of Best Practices for Apache Maven in NetBeans IDE.
Notes for NetBeans IDE 7.1 and earlier versions of the IDE.
  • Choose Window > Other > Maven Repositories Browser to view Maven repositories.
  • You can use the buttons in the toolbar of the Maven Repositories Browser to update indexes and search for artifacts.

Creating the Maven Application

In this tutorial you create a simple Java Swing application project called DVDStoreAdmin. You will create the project from one of the bundled Maven archetypes and then modify the default project settings.

Choosing an Archetype

The New Project wizard enables you to create a Maven project from a Maven archetype. The IDE includes several archetypes for common NetBeans project types, but you can also locate and choose archetypes in remote repositories in the wizard.
  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu to open the New Project wizard. 
  2. Select Java Application from the Maven category. Click Next.
    Screenshot of Maven Archetypes in New Project wizard
  3. Type DVDStoreAdmin for the project name and set the project location.
  4. Modify the default Group Id and Version (optional).
    The Group Id and Version will be used as the coordinates for the artifact in your local repository when you build the project.
  5. Click Finish.
When you click finish the IDE creates the Maven project and opens the project in the Projects window. The IDE automatically creates the class App.java in the com.mycompany.dvdstoreadmin package. You can delete App.java because the application does not need it.
Note. If this is the first time you are creating a Maven project, Maven will need to download some necessary plugins and artifacts to the local repository. This can take some time.

Modifying Project Properties

When you create a Maven project using the wizard, the default project properties are based on the archetype. In some cases, you may need to modify the default properties according to your system and the project's requirements. For example, for this project you want to confirm that the Source level is set to 1.5 or higher because the project uses annotations.
  1. Right-click the project node and choose Properties.
  2. Select the Sources category in the Properties window.
  3. Confirm that the Source/Binary Format that is selected in the drop-down list is 1.5 or higher.
  4. Select UTF-8 from the drop-down list for the Encoding property. Click OK. 

Adding Hibernate Files and Dependencies

To add support for Hibernate you need to make the Hibernate libraries available by declaring the necessary artifacts as dependencies in the POM. The IDE includes wizards to help you create the Hibernate files you may need in your project. You can use the wizards in the IDE to create a Hibernate configuration file and a utility helper class. If you create the Hibernate configuration file using a wizard the IDE automatically updates the POM to add the Hibernate dependencies to the project.
You can add dependencies to the project in the Projects window or by editing pom.xml directly. To add a dependency in the Projects window, right-click the Dependencies node in the Projects window and choose Add Dependency from the popup menu to open the Add Dependency dialog box. When you add a dependency, the IDE updates the POM and downloads any required artifacts to the local repository that are not already present locally.
To edit pom.xml directly, open the file by expanding the Project Files node in the Projects window and double-clicking pom.xml.

Creating the Hibernate Configuration File

The Hibernate configuration file (hibernate.cfg.xml) contains information about the database connection, resource mappings, and other connection properties. When you create a Hibernate configuration file using a wizard you specify the database connection by choosing from a list of database connection registered with the IDE. When generating the configuration file the IDE automatically adds the connection details and dialect information based on the selected database connection. The IDE also automatically modifies the POM to add the required Hibernate dependencies. After you create the configuration file you can edit the file using the multi-view editor, or edit the XML directly in the XML editor.
  1. Right-click the Sakila database connection in the Services window and choose Connect.
  2. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.
  3. Select Hibernate Configuration Wizard from the Hibernate category. Click Next.
  4. Keep the default file name (hibernate.cfg).
  5. Click Browse and specify the src/main/resources directory as the Location (if not already specified). Click Next.
  6. Select the sakila connection in the Database Connection drop down list. Click Finish.
Screenshot of create database connection
When you click Finish the IDE opens hibernate.cfg.xml in the editor. The configuration file contains information about a single database.
If you expand the Dependencies node in the Projects window you can see that the IDE added the required Hibernate artifacts. The IDE lists all direct and transitive dependencies required to compile the project under the Dependencies node. The artifacts that are direct dependencies (dependencies that are specified in the project's POM) are indicated by color JAR icons. An artifact is greyed out if it is a transitive dependency (an artifact that is the dependency of one or more direct dependencies). 
Screenshot of dependencies under Libraries node in Projects window
You can view details of artifacts by right-clicking a JAR and choosing View Artifact Details. The Artifact Viewer contains tabs that provide details about the selected artifact. For example, the Basic tab provides details about the artifact's coordinates and available versions. The Graph tab provides a visual representation of the dependencies of the selected artifact.
Screenshot of Graphs tab or Artifact Viewer showing dependencies
You can also use the Graphs tab to discover and resolve version conflicts among dependencies.

Modifying the Hibernate Configuration File

In this exercise you will edit the default properties specified in hibernate.cfg.xml to enable debug logging for SQL statements. This exercise is optional.
  1. Open hibernate.cfg.xml in the Design tab. You can open the file by expanding the Configuration Files node in the Projects window and double-clicking hibernate.cfg.xml.
  2. Expand the Configuration Properties node under Optional Properties.
  3. Click Add to open the Add Hibernate Property dialog box.
  4. In the dialog box, select the hibernate.show_sql property and set the value to true. Click OK. This enables the debug logging of the SQL statements.
    Add Hibernate Property dialog box the hibernate.show_sql property
  5. Click Add under the Miscellaneous Properties node and select hibernate.query.factory_class in the Property Name dropdown list.
  6. Type org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory in the text field. Click OK.
    Note. Do not select the value from the drop-down list.
    Add Hibernate Property dialog box for properties hibernate.query.factory_class
    If you click the XML tab in the editor you can see the file in XML view. Your file should look similar to the following:
    <hibernate-configuration>
        <session-factory name="session1">
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sakila</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">######</property>
            <property name="hibernate.show_sql">true</property>
            <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
        </session-factory>
    </hibernate-configuration>
  7. Save your changes to the file.
When you run your project you will be able to see the SQL query printed in the IDE's Output window.

Creating the HibernateUtil.java Helper File

To use Hibernate you need to create a helper class that handles startup and that accesses Hibernate's SessionFactory to obtain a Session object. The class calls Hibernate's configure() method, loads the hibernate.cfg.xml configuration file and then builds the SessionFactory to obtain the Session object.
In this section you use the New File wizard to create the helper class HibernateUtil.java.
  1. Right-click the Source Packages node and select New > Other to open the New File wizard.
  2. Select Hibernate from the Categories list and HibernateUtil.java from the File Types list. Click Next.
  3. Type HibernateUtil for the class name and sakila.util as the package name. Click Finish.
Screenshot of create Hibernate Util wizard
When you click Finish, HibernateUtil.java opens in the editor. You can close the file because you do not need to edit the file.

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a plain old Java object (POJO), Actor.java, to represent the data in the table ACTOR in the database. The class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map Actor.java to the ACTOR table you can use a Hibernate mapping file or use annotations in the class.
You can use the Reverse Engineering wizard and the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables that you select. Alternatively, you can use wizards in the IDE to help you create individual POJOs and mapping files from scratch.
Note. When you want to create files for multiple tables you will most likely want to use the wizards. In this tutorial you only need to create one POJO and one mapping file so it is fairly easy to create the files individually. You can see the steps for creating the POJOs and mapping files individually at the end of this tutorial.

Create Reverse Engineering File

To use the POJOs and Mapping Files from Database wizard, you need to first create the reveng.xml reverse engineering file in the src/main/resources directory where you created hibernate.cfg.xml.
  1. Right-click the Source Packages node and select New > Other to open the New File wizard.
  2. Select Hibernate from the Categories list and Hibernate Reverse Engineering Wizard from the File Types list. Click Next.
  3. Type hibernate.reveng for the file name.
  4. Specify src/main/resources as the Location. Click Next.
  5. Select actor in the Available Tables pane and click Add. Click Finish.
The wizard generates a hibernate.reveng.xml reverse engineering file. You can close the reverse engineering file because you will not need to edit the file.
Note. This project requires a MySQL connector jar library (mysql-connector-jar-5.1.13.jar, for example). If a suitable JAR is not listed as a project dependency under the Dependencies node, you can add the dependency by right-clicking the Dependencies node and choosing Add Dependency.

Creating Hibernate Mapping Files and POJOs From a Database

The Hibernate Mapping Files and POJOs from a Database wizard generates files based on tables in a database. When you use the wizard, the IDE generates POJOs and mapping files for you based on the database tables specified in hibernate.reveng.xml and then adds the mapping entries to hibernate.cfg.xml. When you use the wizard you can choose the files that you want the IDE to generate (only the POJOs, for example) and select code generation options (generate code that uses EJB 3 annotations, for example).
  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.
  2. Select Hibernate Mapping Files and POJOs from a Database in the Hibernate category. Click Next.
  3. Select hibernate.cfg.xml from the Hibernate Configuration File dropdown list, if not selected.
  4. Select hibernate.reveng.xml from the Hibernate Reverse Engineering File dropdown list, if not selected.
  5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.
  6. Type sakila.entity for the Package name. Click Finish.
Generate Hibernate Mapping Files and POJOs wizard
When you click Finish, the IDE generates the POJO Actor.java with all the required fields in the src/main/java/sakila/entity directory. The IDE also generates a Hibernate mapping file in the src/main/resources/sakila/entity directory and adds the mapping entry to hibernate.cfg.xml.
Now that you have the POJO and necessary Hibernate-related files you can create a simple Java GUI front end for the application. You will also create and then add an HQL query that queries the database to retrieve the data. In this process we also use the HQL editor to build and test the query.

Creating the Application GUI

In this exercise you will create a simple JFrame Form with some fields for entering and displaying data. You will also add a button that will trigger a database query to retrieve the data.
If you are not familiar with using the GUI builder to create forms, you might want to review the Introduction to GUI Building tutorial.

Creating the JFrame Form

  1. Right-click the project node in the Projects window and choose New > Other to open the New File wizard.
  2. Select JFrame Form from the Swing GUI Forms category. Click Next.
  3. Type DVDStoreAdmin for the Class Name and type sakila.ui for the Package. Click Finish.
When you click Finish, the IDE creates the class and opens the JFrame Form in the Design view of the editor.

Adding Elements to the Form

You now need to add the UI elements to the form. When the form is open in Design view in the editor, the Palette appears in the right side of the IDE. To add an element to the form, drag the element from the Palette into the form area. After you add an element to the form you need to modify the default value of the Variable Name property for that element.
  1. Drag a Label element from the Palette and change the text to Actor Profile
  2. Drag a Label element from the Palette and change the text to First Name.
  3. Drag a Text Field element next to the First Name label and delete the default text.
    When you delete the default text, the text field will collapse. You can resize the text field later to adjust the alignment of the form elements.
  4. Drag a Label element from the Palette and change the text to Last Name.
  5. Drag a Text Field element next to the Last Name label and delete the default text.
  6. Drag a Button element from the Palette and change the text to Query.
  7. Drag a Table element from the Palette into the form.
  8. Modify the Variable Name values of the following UI elements according to the values in the following table.
    You can modify the Variable Name value of an element by right-clicking the element in the Design view and then choosing Change Variable Name. Alternatively, you can change the Variable Name directly in the Inspector window.
    You do not need to assign Variable Name values to the Label elements.
    ElementVariable Name
    First Name text fieldfirstNameTextField
    Last Name text fieldlastNameTextField
    Query buttonqueryButton
    TableresultTable
  9. Resize the text fields and align the form elements.
    You can enable the Horizontal Resizable property for the text fields to ensure that the text fields resize with the window and that the spacing between elements remains constant.
  10. Save your changes.
In Design view your form should look similar to the following image.
GUI form in Design view of the editor
Now that you have a form you need to create the code to assign events to the form elements. In the next exercise you will construct queries based on Hibernate Query Language to retrieve data. After you construct the queries you will add methods to the form to invoke the appropriate query when the Query button is pressed.

Creating the Query in the HQL Query Editor

In the IDE you can construct and test queries based on the Hibernate Query Language (HQL) using the HQL Query Editor. As you type the query the editor shows the equivalent (translated) SQL query. When you click the 'Run HQL Query' button in the toolbar, the IDE executes the query and shows the results at the bottom of editor.
In this exercise you use the HQL Editor to construct simple HQL queries that retrieve a list of actors' details based on matching the first name or last name. Before you add the query to the class you will use the HQL Query Editor to test that the connection is working correctly and that the query produces the desired results. Before you can run the query you first need to compile the application.
  1. Right-click the project node and choose Build.
    When you click Build, the IDE will download the necessary artifacts to your local Maven repository.
  2. Expand the <default package> source package node under the Other Sources node in the Projects window.
  3. Right-click hibernate.cfg.xml and choose Run HQL Query to open the HQL Editor.
  4. Test the connection by typing from Actor in the HQL Query Editor. Click the Run HQL Query button ( Run HQL Query button ) in the toolbar.
    When you click Run HQL Query you should see the query results in the bottom pane of the HQL Query Editor.
    HQL Query Editor showing HQL query results
  5. Type the following query in the HQL Query Editor and click Run HQL Query to check the query results when the search string is 'PE'.
    from Actor a where a.firstName like 'PE%'
    The query returns a list of actors' details for those actors whose first names begin with 'PE'.
    If you click the SQL button above the results you should see the following equivalent SQL query.
    select actor0_.actor_id as col_0_0_ from sakila.actor actor0_ where (actor0_.first_name like 'PE%' )
  6. Open a new HQL Query Editor tab and type the following query in the editor pane. Click Run HQL Query.
    from Actor a where a.lastName like 'MO%'
    The query returns a list of actors' details for those actors whose last names begin with 'MO'.
Testing the queries shows that the queries return the desired results. The next step is to implement the queries in the application so that the appropriate query is invoked by clicking the Query button in the form.

Adding the Query to the Form

You now need to modify DVDStoreAdmin.java to add the query strings and create the methods to construct and invoke a query that incorporates the input variables. You also need to modify the button event handler to invoke the correct query and add a method to display the query results in the table.
  1. Open DVDStoreAdmin.java and click the Source tab.
  2. Add the following query strings (in bold) to the class. 
    public DVDStoreAdmin() {
        initComponents();
    }
    
    private static String QUERY_BASED_ON_FIRST_NAME="from Actor a where a.firstName like '";
    private static String QUERY_BASED_ON_LAST_NAME="from Actor a where a.lastName like '";
    It is possible to copy the queries from the HQL Query Editor tabs into the file and then modify the code.
  3. Add the following methods to create the query based on the user input string.
    private void runQueryBasedOnFirstName() {
        executeHQLQuery(QUERY_BASED_ON_FIRST_NAME + firstNameTextField.getText() + "%'");
    }
        
    private void runQueryBasedOnLastName() {
        executeHQLQuery(QUERY_BASED_ON_LAST_NAME + lastNameTextField.getText() + "%'");
    }
    The methods call a method called executeHQLQuery() and create the query by combining the query string with the user entered search string.
  4. Add the executeHQLQuery() method. 
    private void executeHQLQuery(String hql) {
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            Query q = session.createQuery(hql);
            List resultList = q.list();
            displayResult(resultList);
            session.getTransaction().commit();
        } catch (HibernateException he) {
            he.printStackTrace();
        }
    }
    The executeHQLQuery() method calls Hibernate to execute the selected query. This method makes use of the HibernateUtil.java utility class to obtain the Hibernate Session.
  5. Fix your imports to add import statements for the Hibernate libraries (org.hibernate.Queryorg.hibernate.Session) and java.util.List.
  6. Create a Query button event handler by switching to the Design view and double-clicking the Query button.
    The IDE creates the queryButtonActionPerformed method and displays the method in the Source view.
  7. Modify the queryButtonActionPerformed method in the Source view by adding the following code so that a query is run when the user clicks the button.
    private void queryButtonActionPerformed(java.awt.event.ActionEvent evt) {
        if(!firstNameTextField.getText().trim().equals("")) {
            runQueryBasedOnFirstName();
        } else if(!lastNameTextField.getText().trim().equals("")) {
            runQueryBasedOnLastName();
        }
    }
  8. Add the following method to display the results in the JTable.
    private void displayResult(List resultList) {
        Vector<String> tableHeaders = new Vector<String>();
        Vector tableData = new Vector();
        tableHeaders.add("ActorId"); 
        tableHeaders.add("FirstName");
        tableHeaders.add("LastName");
        tableHeaders.add("LastUpdated");
    
        for(Object o : resultList) {
            Actor actor = (Actor)o;
            Vector<Object> oneRow = new Vector<Object>();
            oneRow.add(actor.getActorId());
            oneRow.add(actor.getFirstName());
            oneRow.add(actor.getLastName());
            oneRow.add(actor.getLastUpdate());
            tableData.add(oneRow);
        }
        resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));
    }
  9. Fix your imports (Ctrl+Shift+I) to add java.util.Vector and save your changes.
After you save the form you can run the project.

Running a Maven Project

Now that the coding is finished, you can build the project and launch the application. When you build a Maven project in the IDE, Maven reads the project's POM to identify the project dependencies. All the artifacts specified as dependencies must be in your local Maven repository in order to build the project. If a required artifact is not in the local repository, Maven will checkout the artifact from a remote repository before attempting to build and run the project. After building the project, Maven will install the resulting binary as an artifact in your local repository.
Notes.
  • Building and running a project for the first time can take some time if the IDE needs to checkout any project dependencies. Subsequent builds will be much faster.
  • To run this application, you first need to specify the Main Class.
To compile and launch this application, perform the following tasks.
  1. Right-click the project node in the Projects window and choose Properties.
  2. Select the Run category in the Project Properties dialog box.
  3. Type sakila.ui.DVDStoreAdmin for the Main Class. Click OK.
    Alternatively, you can click the Browse button and choose the main class in the dialog box.
    Setting the main class in the Browse Main Classes dialog
  4. Click Run Project in the main toolbar to launch the application.
When you invoke the Run action on a Maven project in the IDE, the IDE runs the Maven goals associated with the Run action. The IDE has default goals bound to IDE actions according to the project packaging. You can view the goals bound to the Run action in the Actions pane of the project's Properties window
Actions pane of DVDStoreAdmin project properties window
You can customize the binding of goals to actions in the Actions pane of the project's Properties window.
The GUI form opens when you launch the application. Type in a search string in the First Name or Last Name text field and click Query to search for an actor and see the details. 
DVDStoreAdmin application showing results
If you look in the Output window of the IDE you can see the SQL query that retrieved the displayed results.

Downloading the Solution Project

You can download the solution to this tutorial as a project in the following ways.
  • Download a zip archive of the finished project.
  • Checkout the project sources from the NetBeans Samples by performing the following steps:
    1. Choose Team > Subversion > Checkout from the main menu.
    2. In the Checkout dialog box, enter the following Repository URL:
      https://svn.netbeans.org/svn/samples~samples-source-code
      Click Next.
    3. Click Browse to open the Browse Repostiory Folders dialog box.
    4. Expand the root node and select samples/java/DVDStoreAdmin-Maven. Click OK.
    5. Specify the Local Folder for the sources (the local folder must be empty).
    6. Click Finish.
      When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.
    7. Click Open Project in the dialog that appears when checkout is complete.
    Notes.

Creating POJOs and Mapping Files Individually

Because a POJO is a simple Java class you can use the New Java Class wizard to create the class and then edit the class in the source editor to add the necessary fields and getters and setters. After you create the POJO you then use a wizard to create a Hibernate mapping file to map the class to the table and add mapping information to hibernate.cfg.xml. When you create a mapping file from scratch you need to map the fields to the columns in the XML editor.
Note. This exercise is optional and describes how to create the POJO and mapping file that you created with the Hibernate Mapping Files and POJOs from Database wizard.
  1. Right-click the Source Packages node in the Projects window and choose New > Java Class to open the New Java Class wizard.
  2. In the wizard, type Actor for the class name and type sakila.entity for the package. Click Finish.
  3. Make the following changes (displayed in bold) to the class to implement the Serializable interface and add fields for the table columns.
    public class Actor implements Serializable {
        private Short actorId;
        private String firstName;
        private String lastName;
        private Date lastUpdate;
    }
  4. Generate the getters and setters for the fields by placing the insertion cursor in the source editor, typing Alt-Insert and then selecting Getter and Setter.
  5. In the Generate Getters and Setters dialog box, select all the fields and click Generate.
    Generate Getters and Setters dialog box
    In the Generate Getters and Setters dialog box, you can use the Up arrow on the keyboard to move the selected item to the Actor node and then press the Space bar to select all fields in Actor.
  6. Fix your imports and save your changes.
After you create the POJO for the table you will want to create an Hibernate Mapping File for Actor.java.
  1. Right-click the sakila.entity source packages node in the Projects window and choose New > Other to open the New File wizard.
  2. Select Hibernate Mapping Wizard in the Hibernate category. Click Next.
  3. Type Actor.hbm for the File Name and set the Folder to src/main/resources/sakila/entity . Click Next.
  4. Type sakila.entity.Actor for the Class to Map.
  5. Select actor from the Database Table drop down list if not already selected. Click Finish.
    Generate Hibernate Mapping Files wizard
    When you click Finish the Actor.hbm.xml Hibernate mapping file opens in the source editor. The IDE also automatically adds an entry for the mapping resource to hibernate.cfg.xml. You can view the entry details by expanding the Mapping node in the Design view of hibernate.cfg.xml or in the XML view. The mapping entry in the XML view will look like the following:
            <mapping resource="sakila/entity/Actor.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
  6. Map the fields in Actor.java to the columns in the ACTOR table by making the following changes (in bold) to Actor.hbm.xml.
    <hibernate-mapping>
      <class name="sakila.entity.Actor" table="actor">
        <id name="actorId" type="java.lang.Short">
          <column name="actor_id"/>
          <generator class="identity"/>
        </id>
        <property name="firstName" type="string">
          <column length="45" name="first_name" not-null="true"/>
        </property>
        <property name="lastName" type="string">
          <column length="45" name="last_name" not-null="true"/>
        </property>
        <property name="lastUpdate" type="timestamp">
          <column length="19" name="last_update" not-null="true"/>
        </property>
      </class>
    </hibernate-mapping>
    You can use code completion in the editor to complete the values when modifying the mapping file.
    Note: By default, the generated class element has a closing tag. Because you need to add property elements between the opening and closing class element tags, you need to make the following changes (displayed in bold). After making the changes you can then use code completion between the class tags.
    <hibernate-mapping>
      <class name="sakila.entity.Actor" table="actor">
      </class>
    </hibernate-mapping>
  7. Click the Validate XML button in the toolbar and save your changes.

Creating individual POJOs and Hibernate mapping files might be a convenient way to further customize your application.

Fuente: