Chuyển tới nội dung
Home » Hibernate Example In Netbeans | Using Hibernate In A Web Application

Hibernate Example In Netbeans | Using Hibernate In A Web Application

Hibernate with NetBeans

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).

  1. 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.

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 JSF Managed Bean

In this exercise you will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables you to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the


    dvdrental

    source package node and choose New > Other.

  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.

  3. Type FilmController for the Class Name.

You will use the Managed Bean name

filmController

as the value for the

inputText

and

commandButton

in the JSF page

index.xhtml

when calling methods in the bean.

  1. Select dvdrental for the Package.

  2. Type filmController for the Name that will be used for the managed bean.

  3. Set Scope to Session. Click Finish.

When you click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the

@ManagedBean

and

@SessionScoped

annotations.


@ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } }

Note. Note that the name of the managed bean is not explicitly specified. By default, the name of the bean is the same as the class name and begins with a lower-case letter. If you want the name of the bean to be different from the class name, you can explicitly specify the name as a parameter of the

@ManagedBean

annotations (for example,

@ManagedBean(name="myBeanName")

.

  1. Add the following fields (in bold) to the class.


@ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* }

  1. Add the following code (in bold) to create the FilmController instance and retrieve the films.


/** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }*

  1. Add the following methods that are used to display the table and navigate the pages.* public boolean isHasNextPage() { if (endId + pageSize ⇐ recordCount) { return true; } return false; }

    public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; }

    public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return “index”; }

    public String previous() { startId = startId – pageSize; endId = endId – pageSize; recreateModel(); return “index”; }

    public int getPageSize() { return pageSize; }

    public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return “browse”; } public String prepareList(){ recreateModel(); return “index”; } *

The methods that return “index” or “browse” will prompt the JSF navigation handler to try to open a page named

index.xhtml

or

browse.xhtml

. The JSF 2.0 specification enables the use of implicit navigation rules in applications that use Facelets technology. In this application, no navigation rules are configured in

faces-config.xml

. Instead, the navigation handler will try to locate a suitable page in the application.

  1. Add the following methods that access the helper class to retrieve additional film details.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; }

    public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append(” “); totalCast.append(actor.getLastName()); totalCast.append(” “); } return totalCast.toString(); }

    public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }*

  1. Fix your imports (Ctrl-Shift-I) and save your changes.

You can use the code completion in the editor to help you type your code.

Hibernate with NetBeans
Hibernate with NetBeans

Creating the FilmHelper.java Helper Class

You will now create a helper class in the

dvdrental

package that will be used to perform Hibernate queries on the database. You will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After you test the queries you will create methods in the helper class that construct and run the queries. You will then invoke the methods in the helper class from a JSF managed bean.

Creating the Class

In this section you use the New File wizard to create the helper class

FilmHelper.java

in the

dvdrental

package. You will create a Hibernate session by calling

getSessionFactory

in

HibernateUtil.java

and create some helper methods to create queries to retrieve data from the database. You will invoke the helper methods from the JSP pages.

  1. Right-click the


    dvdrental

    source package node and select New > Java Class to open the New File wizard.

  2. Type FilmHelper for the class name.

  3. Confirm that dvdrental is selected as the Package. Click Finish.

  4. Adding the following code (in bold) to create a Hibernate session.


public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* }

  1. Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add any required import statements (


    org.hibernate.Session

    ) and save your changes.

You will now modify

FilmHelper.java

to add methods that query the DB.

Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise you will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. You will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the

filmId

primary key. You will use the HQL editor to construct and test the HQL query. After you have created the correct query you will add a method to the class that can generate the proper query.

  1. Right-click the project node in the Projects window and choose Clean and Build.

  2. Right-click


    hibernate.cfg.xml

    in the Projects window and choose Run HQL Query to open the HQL query editor.

  3. Select hibernate.cfg from the drop down list in the toolbar.

  4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( images:./run_hql_query_16.png[title=”Run HQL Query button”] ) in the toolbar.


from Film

When you click Run HQL Query you can see the results of the query in the bottom window of the HQL query editor.

If you click the SQL button you can see the equivalent SQL query.


select film0_.film_id as col_0_0_ from sakila.film film0_

  1. Type the following query to retrieve the records in the Film table where the film id is between 100 and 200.


from Film as film where film.filmId between 100 and 200

The result window displays a list of records. Now that you have tested that the query returns the desired results, you can use the query in the helper class.

  1. Add the following method


    getFilmTitles

    to

    FilmHelper.java

    to retrieve the films where the film id is between a certain range specified by the variables

    startID

    and

    endID

    .


public List getFilmTitles(int startID, int endID) { List

filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'"); filmList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; }


  1. Add the following method


    getActorsByID

    that retrieves the actors in a particular film. The method constructs the query using

    filmId

    as the input variable.


public List getActorsByID(int filmId){ List

actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')"); actorList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; }


  1. Fix your imports and save your changes.

When you fix your imports you want to choose

java.util.List

and

org.hibernate.Query

.

Adding Additional Helper Methods

You will now add additional helper methods that create queries based on an input variable. You can check the queries in the HQL query editor.

  1. Add the following method to retrieve a list of categories according to


    filmId

    .


public Category getCategoryByID(int filmId){ List

categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')"); categoryList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }


  1. Add the following method to retrieve a single film according to


    filmId

    .


public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Film as film where film.filmId=" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; }

  1. Add the following method to retrieve the film language according to


    langId

    .


public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Language as lang where lang.languageId=" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); }

  1. Save your changes.

Benefits of Hibernate

Any changes made are encapsulated in the data source itself, so that when those sources or their application programming interfaces (APIs) change, the applications that use ORM don’t have to make changes or even be aware of that information. Similarly, programmers can have a consistent view of objects over time, although the sources that deliver them, the sinks that receive them and the applications that access them may change.

Hibernate is freely available to download and is licensed under the open source GNU Lesser General Public License (LGPL).

How to Setting Up Hibernate in NetBeans IDE | Java Hibernate Tutorial #Ep01 (2020)
How to Setting Up Hibernate in NetBeans IDE | Java Hibernate Tutorial #Ep01 (2020)

Adding an Option Array Wrapper for the Person List

In this section, you add business logic to the session bean so that your project can access the Person data source using the Hibernate framework. First you add a session bean property to hold an array of

Option

objects for use by the DropDown List component. Then you add code to fill the array of

Option

objects with the results from a query on the Person database table.

  1. In the Outline window, right-click the SessionBean1 and choose Add > Property from the pop-up menu.

    If the Add menu item is disabled, close the pop-up window and try
    again.

  2. In the New Property Pattern dialog box, type

    personOptions

    in the Name text box, type

    Option[]

    in the Type text box, and click OK.

    Note that the newly added property might not appear in the Outline window.
    The property will appear after you open and save the SessionBean1 source file,
    which you do in the following steps.

  3. Double-click the SessionBean1 node to open the

    SessionBean1.java

    source file.

    Error annotations appear in the code as a result of unresolved classes. You can ignore these annotations for now. Later, you use the Fix Imports action to resolve these errors.

  4. Add the following code shown in bold to the end of the

    init

    method in the

    SessionBean1

    class.

    This code calls a query on the Person data source and stores the results in the

    personOptions

    array.

    Code Sample 1: Initializing the

    personOptions

    Array in the Session Bean’s

    init

    Method

    public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // *before* managed components are initialized
    // TODO – add your own initialization code here

    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO – add your own initialization code here
    List personList = null;
    try{
    Session session =
    HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = session.beginTransaction();
    Query q = session.createQuery(“from Person”);
    personList = (List) q.list();
    } catch(Exception e) {
    e.printStackTrace();
    }
    personOptions = new Option[personList.size()];
    Iterator iter = personList.iterator();
    int i=0;
    while (iter.hasNext()) {
    Person person = (Person) iter.next();
    Option opt = new Option(“” + person.getPersonId(),
    person.getName());
    personOptions[i++] = opt;
    }
    }

  5. Right-click in the source and choose Fix Imports from the pop-up menu.

    The Fix Imports dialog appears.

  6. Select the following fully qualified names, and click OK.

    Class Name Fully Qualified Name

    Query

    org.hibernate.Query

    Session

    org.hibernate.Session

    List

    java.util.List

    Iterator

    java.util.Iterator

    Option

    com.sun.webui.jsf.model.Option

    for Java EE 5

    com.sun.rave.web.ui.model.Option

    for J2EE 1.4

    Transaction

    org.hibernate.Transaction
  7. Close and save the file.

See Also

For additional information on creating Swing GUI applications, see the following tutorials.

Using Hibernate in a Web Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Web Application Project
  • Modifying the Hibernate Configuration File
  • Creating the

    HibernateUtil.java

    Helper File
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the

    FilmHelper.java

    Helper Class
  • Creating the JSF Managed Bean
  • Creating the Web Pages
  • Running the Project
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a JSF managed bean and JSF 2.0 pages to display the data.

Before starting this tutorial you may want to familiarize yourself with the following documents.

  • Hibernate documentation at hibernate.org

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.1, 7.2, 7.3, 7.4, Java EE version

Version 6 or 7

GlassFish Server Open Source Edition

3.x or 4.x

Version 5.x

Sakila Database

Plugin available from update center

You can download a zip archive of the finished project.

HIbernate Tutorial using netbeans
HIbernate Tutorial using netbeans

Adding Hibernate Support to the Project

To add support for Hibernate to a J2SE project you need to add the Hibernate library to the project. The Hibernate library is included with the IDE and can be added to any project by right-clicking the ‘Libraries’ node in the Projects window, selecting ‘Add Library’ and then selecting the Hibernate library in the Add Library dialog box.

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 adds the Hibernate libraries to the project.

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 adds the Hibernate library to the project classpath. 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 Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Configuration Wizard from the Hibernate category. Click Next.

  3. Keep the default settings in the Name and Location pane (you want to create the file in the


    src

    directory). Click Next.

  4. Select the sakila connection in the Database Connection drop down list. Click Finish.

When you click Finish the IDE opens

hibernate.cfg.xml

in the source editor. The IDE creates the configuration file at the root of the context classpath of the application (in the Files window, WEB-INF/classes). In the Projects window the file is located in the source package. The configuration file contains information about a single database. If you plan to connect to multiple databases, you can create multiple configuration files in the project, one for each database servers, but by default the helper utility class will use the

hibernate.cfg.xml

file located in the root location.

If you expand the Libraries node in the Projects window you can see that the IDE added the required Hibernate JAR files and the MySQL connector JAR.

Note. NetBeans IDE 8.0 bundles the Hibernate 4 libraries. Older versions of the IDE bundled Hibernate 3.

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.

  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.

  1. Click Add under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Type org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory as the Property Value.

This is the translator factory class that is used in Hibernate 4 that is bundled with the IDE.

Click OK.

If you are using NetBeans IDE 7.4 or earlier you should select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value in the dialog box. NetBeans IDE 7.4 and earlier bundled Hibernate 3.

If you click the XML tab in the editor you can see the file in XML view. Your file should look like the following:



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### true org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

  1. Save your changes to the file.

After you create the form and set it as the main class you will be able to see the SQL query printed in the IDE’s Output window when you run the project.

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.

  1. Type HibernateUtil for the class name and sakila.util as the package name. Click Finish.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

What is Hibernate?

Hibernate is an open source object relational mapping (ORM) tool that provides a framework to map object-oriented domain models to relational databases for web applications.

Object relational mapping is based on the containerization of objects and the abstraction that provides that capacity. Abstraction makes it possible to address, access and manipulate objects without having to consider how they are related to their data sources.

The Hibernate ORM framework guides mapping Java classes to database tables and Java data types to SQL data types and provides querying and retrieval.

Complete Hibernate Framework Full Courses tutorials with example In One Video | Hibernate  in Hindi
Complete Hibernate Framework Full Courses tutorials with example In One Video | Hibernate in Hindi

Adding the Object List Data Provider Wrapper for the Trips List

In this section you extend the

ObjectListDataProvider

class to build a

TripDataProvider

wrapper for the results from a trips query.

  1. In the Projects window, right-click HibernateTutorialApp >
    Source Packages > hibernatetutorialapp and choose New > Java Class.
  2. Name the class

    TripDataProvider

    and click Finish.

    A TripDataProvider.java node appears under the hibernatetutorialapp package node and the IDE displays the source code for the

    TripDataProvider

    class.

  3. Replace the class definition with the following code.

    Code Sample 2:

    TripDataProvider

    Class

    public class TripDataProvider extends ObjectListDataProvider{
    private ArrayList tripsList = new ArrayList();
    // Note: to eliminate warnings when using Java SE 1.5, use instead
    // private ArrayList
    tripsList = new ArrayList
    ();
    /** Creates a new instance of tripDataProvider */
    public TripDataProvider() {
    // Put in dummy data for design time
    tripsList.add(new Trip());
    // Wrap the list
    setList(tripsList);
    }
    public void refreshTripsList(Integer personId){
    tripsList.clear();
    try{
    Session session =
    HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = session.beginTransaction();
    Person person =
    (Person)
    session.load(Person.class, personId);
    Set personTrips = (PersistentSet)person.getTrips();
    tripsList.addAll(personTrips);
    tx.commit();
    } catch(Exception e){
    e.printStackTrace();
    }
    }
    }

  4. Right-click in the source and choose Fix Imports from the pop-up menu.
  5. Select the following fully qualified names, and click OK.

    Class Name Fully Qualified Name

    Session

    org.hibernate.Session

    Transaction

    org.hibernate.Transaction

    Set

    java.util.Set
  6. Close and save the file.
  7. In the Outline window, right-click the SessionBean1 node and choose Add > Property from the pop-up menu.
  8. In the New Property Pattern dialog box, type

    tripDataProvider

    in the Name text box, type

    TripDataProvider

    in the Type text box, and click OK.
  9. Double-click the SessionBean1 node to open the

    SessionBean1.java

    source file.
  10. In the Navigation window, double-click the tripDataProvider node.

    The IDE scrolls the source code to the declaration for the tripDataProvider property.

  11. Replace the declaration for the

    tripDataProvider

    property with the following statement:


    private TripDataProvider tripDataProvider = new TripDataProvider();

  12. Press F11 to build the project.
  13. Close and reopen the project.

    You must close and reopen the project to make the new data provider appear in the list of available data providers.

Creating a Hibernate Class Library

You begin this tutorial by downloading the Hibernate library files and using the Library Manager tool to make the required Hibernate libraries available to the IDE.

  1. Download

    hibernate-3.2.2.ga.zip

    from hibernate and extract the files. Note: The examples in this tutorial use Hibernate 3.2.2 and the associated JAR files that are provided with that version. If you use a different version, the JAR library names and version numbers might vary. In addition, the list of JAR libraries to add might differ.
  2. In the IDE, choose Tools > Library Manager from the main menu.
  3. Click New Library, type

    Hibernate322

    in the Library Name field, and click OK.
  4. Click Add JAR/Folder and navigate to the directory into which you extracted the Hibernate files.
  5. Select

    hibernate3.jar

    and press Enter.
  6. Click Add JAR/Folder again, and navigate into the

    lib

    subdirectory.
  7. Use Ctrl-Click to select the following 10 JAR files and press Enter. If you are using a different version than 3.2.2, consult Hibernate’s web site to determine which JAR files to select.


    • ant-1.6.5.jar

    • antlr-2.7.6.jar

    • asm-attrs.jar

    • asm.jar

    • cglib-2.1.3.jar

    • commons-logging-1.0.4.jar

    • commons-collections-2.1.1.jar

    • dom4j-1.6.1.jar

    • ehcache-1.2.3.jar

    • jdbc2_0-stdext.jar

    The following figure shows the Hibernate library in the Library Manager window.

    Figure 1: Library Manager Window Showing the Hibernate Library
  8. If you are deploying your application to the Tomcat server, you must
    also add

    jta.jar

    from the Hibernate

    lib

    directory.
  9. To make the Hibernate Javadoc available to the Java Editor, select the Javadoc tab, click Add Zip/Folder, navigate to the directory into which you extracted the Hibernate files, select the

    doc/api

    subdirectory, and press Enter.
  10. (Optional) If you want to step into Hibernate classes during a debugging session, click the Sources tab, click Add JAR/Folder, navigate to the directory into which you extracted the Hibernate files, select the

    src

    subdirectory, and press Enter.
  11. Click OK to close the Library Manager.
New Diff Coffee Lv280 All New Equipment Giant Pelulu Valentine's Event 2024 | Toram Online| Xen'Rani
New Diff Coffee Lv280 All New Equipment Giant Pelulu Valentine’s Event 2024 | Toram Online| Xen’Rani

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.

  2. Expand the

    source package 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 () in the toolbar.

When you click Run HQL Query you should see the query results in the bottom pane of the HQL Query Editor.

  1. 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%' )

  1. 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.

History of Hibernate

Hibernate was started in 2001 by Gavin King with colleagues from Cirrus Technologies as an alternative to using EJB2-style entity beans. The original goal was to offer better persistence capabilities than those offered by EJB2.

In early 2003, the Hibernate development team began Hibernate2 releases. In 2005, Hibernate version 3.0 was released. In December 2018, Hibernate ORM 5.4.0 Final was released.

Using Hibernate in a Java Swing Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Java Swing Application Project
  • Adding Hibernate Support to the Project
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the Application GUI
  • Creating the Query in the HQL Query Editor
  • Adding the Query to the Form
  • Running the Project
  • Creating POJOs and Mapping Files Individually
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a Java Swing application that displays data from a database. The application uses the Hibernate framework as the persistence layer to retrieve POJOs (plain old Java objects) from a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates the support for the Hibernate framework included in the IDE and how to use wizards to create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a GUI interface for searching and displaying the data.

The application that you build in this tutorial is a companion administration application for the DVD Store web application. This tutorial covers how to create an application that allows you to query an actor’s profile based on the match with first name or last name. If you wish you can extend the application to query film details and to add/update/delete items. This tutorial uses MySQL and the Sakila database, but you can use any supported database server with Hibernate applications. The Sakila database is a sample database that you can download from the MySQL site. Information for setting up the Sakila DB is provided in the following sections.

Before starting this tutorial you may want to familiarize yourself with the following documentation.

  • Hibernate documentation at hibernate.org.

  • Connecting to a MySQL Database tutorial.

To build this application using Maven, see Creating a Maven Swing Application Using Hibernate.

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.2, 7.3, 7.4, 8.0, Java

version 7 or 8

version 5.x

Sakila Database

plugin available from update center

You can download a zip archive of the finished project.

Spring Boot Simple Project step by step using Mysql Database
Spring Boot Simple Project step by step using Mysql Database

Creating the Web Pages

In this exercise you will create two web pages for displaying the data. You will modify the

index.xhtml

generated by the IDE to add a table that displays the films in the database. You will then create

browse.xhtml

to display a film’s details when you click the “View” link in the table. You will also create a JSF template page that is used by

index.xhtml

and

browse.xhtml

.

For more about using JSF 2.0 and Facelets templates, see Introduction to JavaServer Faces 2.0

Creating template.xhtml

You will first create the JSF Facelets template

template.xhtml

that is used in the composition of the

index.xhtml

and

browse.xhtml

pages.

  1. Right-click the DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template in the JavaServer Faces category. Click Next.

  3. Type template for the File Name and choose the first CSS layout style.

  4. Click Finish.

When you click Finish, the file

template.xhtml

opens in the editor. The template contains the following default code.



Top

Content


  1. Modify the

    element to change the default generated name to “body”.


Content

  1. Save your changes.

The content enclosed within the element in

index.xhtml

and

browse.xhtml

will be inserted into the location identified with


Content


in the template.

Modifying index.xhtml

When you created the web application, the IDE automatically generated the page

index.xhtml

. In this exercise you modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

  1. Expand the Web Pages folder in the Projects window and open


    index.xhtml

    in the editor.

The New Project wizard generated the following default

index.xhtml

page.




<br /> Facelet Title<br />


Hello from Facelets


  1. Modify the page to use the JSF

    andelements and add aelement.

When you start typing the tags, the IDE adds

xmlns:ui="http://java.sun.com/jsf/facelets"

tag library declaration.

The and elements are used in combination with the page template that you will create. The element references the location of the template that will be used by this page. The element references the position in the template that the enclosed code will occupy.

  1. Add the following navigation links that call the


    previous

    and

    next

    methods in the JSF managed bean.




* *


  1. Add the following


    dataTable

    element (in bold) to generate the table to display the retrieved items.



* *

  1. Save your changes.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the

prepareView

method in the managed bean. The

prepareView

method returns “browse” and will open

browse.xhtml

.

Note. When you type the tag, the IDE will add

xmlns:f="http://java.sun.com/jsf/core

tag library declaration. Confirm that the tag library is declared in the file.

Creating browse.xhtml

You will now create the

browse.xhtml

page for displaying details of the selected film. You can use the Facelets Template Client wizard to create the page based on the JSF Facelets template

template.xhtml

that you created.

  1. Right-click DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template Client in the JavaServer Faces category. Click Next.

  1. Type browse for the File Name.

  2. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.

  3. Expand the Web Pages folder and select


    template.xhtml

    . Click Select File.

  1. Select

    for the Generated Root Tag. Click Finish.

When you click Finish, the file

browse.xhtml

opens in the editor with the following code.




top


body


You can see that the new file specifies the

template.xhtml

file and that the tag has the property

name="body"

  1. Add the following code (in bold) between the

    tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.




top


* *


You can see that

browse.xhtml

and

index.xhtml

will use the same page template.

  1. Save your changes.

Creating the Database

This tutorial uses a MySQL database called

sakila

, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when you install the IDE so you need to first create the database to follow this tutorial.

To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin 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 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.

When you click OK a Sakila node appears under the MySQL Server node.

  1. 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.

Java Simple Project step by step using mysql database
Java Simple Project step by step using mysql database

Adding Hibernate Support to the Project

To add support for Hibernate to a J2SE project you need to add the Hibernate library to the project. The Hibernate library is included with the IDE and can be added to any project by right-clicking the ‘Libraries’ node in the Projects window, selecting ‘Add Library’ and then selecting the Hibernate library in the Add Library dialog box.

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 adds the Hibernate libraries to the project.

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 adds the Hibernate library to the project classpath. 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 Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Configuration Wizard from the Hibernate category. Click Next.

  3. Keep the default settings in the Name and Location pane (you want to create the file in the


    src

    directory). Click Next.

  4. Select the sakila connection in the Database Connection drop down list. Click Finish.

When you click Finish the IDE opens

hibernate.cfg.xml

in the source editor. The IDE creates the configuration file at the root of the context classpath of the application (in the Files window, WEB-INF/classes). In the Projects window the file is located in the source package. The configuration file contains information about a single database. If you plan to connect to multiple databases, you can create multiple configuration files in the project, one for each database servers, but by default the helper utility class will use the

hibernate.cfg.xml

file located in the root location.

If you expand the Libraries node in the Projects window you can see that the IDE added the required Hibernate JAR files and the MySQL connector JAR.

Note. NetBeans IDE 8.0 bundles the Hibernate 4 libraries. Older versions of the IDE bundled Hibernate 3.

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.

  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.

  1. Click Add under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Type org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory as the Property Value.

This is the translator factory class that is used in Hibernate 4 that is bundled with the IDE.

Click OK.

If you are using NetBeans IDE 7.4 or earlier you should select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value in the dialog box. NetBeans IDE 7.4 and earlier bundled Hibernate 3.

If you click the XML tab in the editor you can see the file in XML view. Your file should look like the following:



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### true org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

  1. Save your changes to the file.

After you create the form and set it as the main class you will be able to see the SQL query printed in the IDE’s Output window when you run the project.

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.

  1. Type HibernateUtil for the class name and sakila.util as the package name. Click Finish.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

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.

  1. 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

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.

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.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/java/DVDStoreAdmin-Maven. Click OK.

      3. Specify the Local Folder for the sources (the local folder must be empty).

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Notes.

  • Steps for checking out sources from Kenai only apply to NetBeans IDE 6.7 and 6.8.

  • You need a Subversion client to checkout the sources from Kenai. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Hibernate Tutorial For Beginners | What Is Hibernate Framework | Java Training | Edureka
Hibernate Tutorial For Beginners | What Is Hibernate Framework | Java Training | Edureka

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.

When you click OK a Sakila node appears under the MySQL Server node.

  1. 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.

Running the Project

Now that the coding is finished, you can launch the application. Before you run the project, you need to specify the application’s Main Class in the project’s properties dialog box. If no Main Class is specified, you are prompted to set it the first time that you run the application.

  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.

  1. Click Run Project in the main toolbar to 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.

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.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/java/DVDStoreAdmin-Ant. Click OK.

      3. Specify the Local Folder for the sources (the local folder must be empty).

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Note. You need a Subversion client to checkout the sources. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

JPA And Hibernate Tutorial For Beginners with Spring Boot and Spring Data JPA
JPA And Hibernate Tutorial For Beginners with Spring Boot and Spring Data JPA

Running the Project

The basics of the application are now complete. You can now run the application to check if everything is working correctly.

  1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL

http://localhost:8080/DVDStore/

that displays the list of films.

  1. In your browser, click “View” to load


    browse.xhtml

    to view the film details.

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.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/javaee/DVDStoreEE6. Click OK.

      3. Specify the Local Folder for the sources.

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Notes. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Troubleshooting

Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, you might want to look at the Troubleshooting section of the Creating a Simple Web Application Using a MySQL Database tutorial or the Connecting to a MySQL Database tutorial.

If you download and run the solution project you might see the following error in the Output window if it is the first time that you have deployed an application that uses the MySQL database.


SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org

In your browser window you might see a

java.lang.ExceptionInInitializerError

and the following stack trace.


java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.

(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ...

The output message states that the JDBC driver for the MySQL database was not found. The most probable reason is that you need to add the MySQL JDBC driver file to your GlassFish server installation. To confirm that the driver is missing, navigate to the

GLASSFISH-INSTALL/glassfish/domains/domain1/lib

directory on your local system (where GLASSFISH-INSTALL is your GlassFish installation directory). If the

domain1/lib

directory does not contain the JDBC driver file (for example,

mysql-connector-java-5.1.13-bin.jar

) you need to copy the JDBC driver to the directory. The MySQL JDBC driver is not added to your GlassFish installation when you install the server.

You can add a copy of the MySQL JDBC driver to your GlassFish installation by performing the following steps.

  1. Download the MySQL Connector/J JDBC driver.

  2. Extract the driver and copy the driver file (for example,


    mysql-connector-java-5.1.13-bin.jar

    ) to the

    domain1/lib

    directory of your GlassFish installation.

Alternatively, when you use the IDE to create an application that uses the MySQL database, the IDE can automatically copy the bundled MySQL JDBC driver to the GlassFish server when you deploy the project, if required. To confirm that the IDE will copy the necessary JDBC drivers, choose Tools > Servers from the main menu to open the Servers manager and confirm that the Enable JDBC Driver Deployment option is selected for your GlassFish server.

After you create and deploy a web application that uses the MySQL database, if you navigate to the

domain1/lib

directory of your local GlassFish installation you will see that directory contains the JDBC driver file.

Hibernate

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.

  1. Expand the

    source package node under the Other Sources node in the Projects window.

  2. Right-click


    hibernate.cfg.xml

    and choose Run HQL Query to open the HQL Editor.

  3. Test the connection by typing


    from Actor

    in the HQL Query Editor. Click the 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.

  1. 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%' )

  1. 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.

#4. Hibernate CRUD Example in Eclipse IDE with Maven and MySQL Database
#4. Hibernate CRUD Example in Eclipse IDE with Maven and MySQL Database

Binding the Components to the Data Wrappers

In this section, you bind the components to the data wrappers and add logic to synchronize the data in the Table component with the selected person.

  1. Open Page1 in the Visual Designer.
  2. Right-click the Drop Down List component and choose Bind to Data from the pop-up menu.
  3. In the Bind to an Object tab, select SessionBean1 > personOptions and click OK.
  4. Right-click the Table component and choose Table Layout from the pop-up menu.
  5. Choose tripDataProvider from the Get Data From drop-down list.

    Note: If tripDataProvider is not available from the drop-down list, build, close, and reopen the project, and try again.

  6. Select personId in the Selected list and click the left-arrow button to move the field from the Selected list to the Available list.
  7. Use the Up and Down buttons to arrange the remaining fields in the following order, as shown in Figure 6, and click OK.

    • tripId
    • depDate
    • depCity
    • destCity
    • tripTypeId
    Figure 6: Binding the Table Component to the

    tripDataProvider

    Wrapper
  8. In the Editing toolbar, click Java to open

    Page1.java

    in the Java Editor.
  9. In the

    prerender

    method, add the following code shown in bold.

    Code Sample 3:

    prerender

    Method

    public void prerender() {
    try {
    if (dropDown1.getSelected() == null ) {
    Option firstPerson = getSessionBean1().getPersonOptions()[0];
    getSessionBean1().getTripDataProvider().refreshTripsList(
    new Integer((String)firstPerson.getValue()));
    }
    } catch (Exception ex) {
    log(“Error Description”, ex);
    error(ex.getMessage());
    }
    }

    This code causes the page to display the information for the first person in the drop-down list when the user first visits the page.

  10. Right-click in the source and choose Fix Imports from the pop-up menu.

    The Fix Imports dialog appears.

  11. In the Fully Qualified Name drop-down list, select

    com.sun.webui.jsf.model.Option

    for Java EE 5
    projects and

    com.sun.rave.web.ui.model.Option

    for J2EE 1.4 projects.
  12. Click OK.
  13. Add the following code shown in bold to the

    dropDown1_processValueChange

    method.

    Code Sample 4:

    dropDown1_processValueChange

    Method

    public void dropDown1_processValueChange(ValueChangeEvent event) {
    try {
    Integer personId =
    new Integer((String)dropDown1.getSelected());
    getSessionBean1().getTripDataProvider().refreshTripsList(
    personId);
    } catch(Exception ex) {
    log(“Error getting Person List : “, ex);
    error(“Error getting Person List: ” + ex.getMessage());
    }
    }

    This code causes the page to display the trips for the selected person.

  14. In the main toolbar, click Run Main Project to run the project.
  15. Select a person’s name from the drop-down list to display that person’s trips.

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.

  1. 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.

  1. 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.

  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate import statements for the Hibernate libraries (


    org.hibernate.Query

    ,

    org.hibernate.Session

    ) and

    java.util.List

    . Save your changes.

  2. 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.

  1. 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(); }* }

  1. Add the following method to display the results in the JTable.


private void displayResult(List resultList) { Vector

tableHeaders = new Vector

(); 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
oneRow = new Vector
(); 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)); }



  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate an import statement for


    java.util.Vector

    and

    java.util.List

    . Save your changes.

After you save the form you can run the project.

Senior Programmers vs Junior Developers #shorts
Senior Programmers vs Junior Developers #shorts

Creating the Database

This tutorial uses a MySQL database called

sakila

, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when you install the IDE so you need to first create the database to follow this tutorial.

To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin 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 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.

When you click OK a Sakila node appears under the MySQL Server node.

  1. 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.

Hibernate and JPAJDBC

Java Database Connectivity (JDBC) is an API packaged with the Java SE edition that makes it possible to standardize and simplify the process of connecting Java applications to external, relational database management systems (RDBMS).

Fundamentally, applications written in Java perform logic. The Java language provides facilities for performing iterative logic with looks, conditional logic with if statements and object-oriented analysis through the use of classes and interfaces. But Java applications do not store data persistently.

Data persistence is typically delegated to NoSQL databases such as MongoDB and Cassandra, or to relational databases such as IBM’s DB2 or Microsoft’s SQL Server or the popular open source database MySQL.

To help address the object-relational impedance mismatch, a number of frameworks exist that simplify the task of moving data between a relational database and a Java program. Popular object-relational mapping (ORM) frameworks include Hibernate, TopLink and DataNucleus. While each framework has its own set of unique capabilities, all of them comply with the Java Persistence API standard, which is now part of the Java EE/Jakarta EE specification.

Code a Hibernate App in 100 minutes |  Hibernate Tutorial For Beginners / Experienced | JPA + MYSQL
Code a Hibernate App in 100 minutes | Hibernate Tutorial For Beginners / Experienced | JPA + MYSQL

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 left 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.

  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.

Element Variable Name

First Name text field

Last Name text field

Query button

Table

  1. Save your changes.

In Design view your form should look similar to the following image.

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.

Running the Project

Now that the coding is finished, you can launch the application. Before you run the project, you need to specify the application’s Main Class in the project’s properties dialog box. If no Main Class is specified, you are prompted to set it the first time that you run the application.

  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.

  1. Click Run Project in the main toolbar to 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.

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.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/java/DVDStoreAdmin-Ant. Click OK.

      3. Specify the Local Folder for the sources (the local folder must be empty).

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Note. You need a Subversion client to checkout the sources. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Spring Boot Thymeleaf Web Application | Full Course ✅ | Student Management System Project
Spring Boot Thymeleaf Web Application | Full Course ✅ | Student Management System Project

Creating the Web Pages

In this exercise you will create two web pages for displaying the data. You will modify the

index.xhtml

generated by the IDE to add a table that displays the films in the database. You will then create

browse.xhtml

to display a film’s details when you click the “View” link in the table. You will also create a JSF template page that is used by

index.xhtml

and

browse.xhtml

.

For more about using JSF 2.0 and Facelets templates, see Introduction to JavaServer Faces 2.0

Creating template.xhtml

You will first create the JSF Facelets template

template.xhtml

that is used in the composition of the

index.xhtml

and

browse.xhtml

pages.

  1. Right-click the DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template in the JavaServer Faces category. Click Next.

  3. Type template for the File Name and choose the first CSS layout style.

  4. Click Finish.

When you click Finish, the file

template.xhtml

opens in the editor. The template contains the following default code.



Top

Content


  1. Modify the

    element to change the default generated name to “body”.


Content

  1. Save your changes.

The content enclosed within the element in

index.xhtml

and

browse.xhtml

will be inserted into the location identified with


Content


in the template.

Modifying index.xhtml

When you created the web application, the IDE automatically generated the page

index.xhtml

. In this exercise you modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

  1. Expand the Web Pages folder in the Projects window and open


    index.xhtml

    in the editor.

The New Project wizard generated the following default

index.xhtml

page.




<br /> Facelet Title<br />


Hello from Facelets


  1. Modify the page to use the JSF

    andelements and add aelement.

When you start typing the tags, the IDE adds

xmlns:ui="http://java.sun.com/jsf/facelets"

tag library declaration.

The and elements are used in combination with the page template that you will create. The element references the location of the template that will be used by this page. The element references the position in the template that the enclosed code will occupy.

  1. Add the following navigation links that call the


    previous

    and

    next

    methods in the JSF managed bean.




* *


  1. Add the following


    dataTable

    element (in bold) to generate the table to display the retrieved items.



* *

  1. Save your changes.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the

prepareView

method in the managed bean. The

prepareView

method returns “browse” and will open

browse.xhtml

.

Note. When you type the tag, the IDE will add

xmlns:f="http://java.sun.com/jsf/core

tag library declaration. Confirm that the tag library is declared in the file.

Creating browse.xhtml

You will now create the

browse.xhtml

page for displaying details of the selected film. You can use the Facelets Template Client wizard to create the page based on the JSF Facelets template

template.xhtml

that you created.

  1. Right-click DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template Client in the JavaServer Faces category. Click Next.

  1. Type browse for the File Name.

  2. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.

  3. Expand the Web Pages folder and select


    template.xhtml

    . Click Select File.

  1. Select

    for the Generated Root Tag. Click Finish.

When you click Finish, the file

browse.xhtml

opens in the editor with the following code.




top


body


You can see that the new file specifies the

template.xhtml

file and that the tag has the property

name="body"

  1. Add the following code (in bold) between the

    tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.




top


* *


You can see that

browse.xhtml

and

index.xhtml

will use the same page template.

  1. Save your changes.

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.

  1. 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.

  1. 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.

  1. Fix your imports to add import statements for the Hibernate libraries (


    org.hibernate.Query

    ,

    org.hibernate.Session

    ) and

    java.util.List

    .

  2. 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.

  1. 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(); }* }

  1. Add the following method to display the results in the JTable.


private void displayResult(List resultList) { Vector

tableHeaders = new Vector

(); 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
oneRow = new Vector
(); 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)); }



  1. 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.

What is Hibernate in Java? | How does Hibernate Work Behind the Scenes? | ORM Framework
What is Hibernate in Java? | How does Hibernate Work Behind the Scenes? | ORM Framework

Creating a Web Project That Uses the Hibernate Framework

In this section, you create a Visual Web project and add the HibernateTravelPOJO Java class project to the web project. The following figure shows the web page that you build in this project.

Figure 3: HibernateTutorialApp Page1
  1. In the Runtime window, expand the Databases node.
  2. Right-click the jdbc node for the Travel database and choose Connect
    from the pop-up menu.
  3. In the Connect dialog box, enter

    travel

    for the Password,
    select Remember Password During This Session, and click OK.
  4. From the main menu, choose File > New Project.
  5. In the New Project Wizard, select Web from the Categories list and select
    Visual Web Application from the Projects list.
  6. Click Next.
  7. Name the project

    HibernateTutorialApp

    , select
    the Server and Java EE Version, and click Finish.

    Your project appears with the initial page (

    Page1

    ) open in the Visual Designer.

  8. In the Projects window, right-click HibernateTutorialApp > Libraries and choose Add Library.
  9. In the Add Library window, select Hibernate322 and click Add Library, as shown in the following figure.

    Figure 4: Adding the Hibernate Library
  10. Right-click HibernateTutorialApp > Libraries again,
    and choose Add Project.
  11. In the Add Project window, navigate to and choose HibernateTravelPOJO, and click Add Project JAR Files, as shown in the following figure.

    Figure 5: Adding the HibernateTravelPOJO Project
  12. Drag a Drop Down List component from the Palette and drop it in the top left corner of Page1 in the Visual Designer.
  13. Double-click the Drop Down List component that you
    just added to Page1.

    The IDE adds a method for processing a change in the drop-down list selection
    and displays the method in the source editor. The IDE also registers
    the method as a handler for the value change event.
    You add code to this method later.

  14. Click Design in the editing toolbar to switch back to the Visual
    Designer.
  15. Right-click the Drop Down List component and select Auto-Submit on Change from the pop-up menu.

    This action causes the browser to submit the page whenever the user chooses a new value from the drop-down list.

  16. Drag and drop a Message Group component to the right of the Drop Down List component.

    Message Group components help you to diagnose runtime problems.

  17. Drag and drop a Table component below the Drop Down List component.

Troubleshooting Tips

If the web application is not working, here are some tips on how to diagnose the problem.

  • If, when you run the application, the table component displays “No
    items found,” make sure that the database server is running,
    that you have connected to the Travel database from the
    Runtime window,
    and that the port setting in the

    hibernate.cfg.xml

    file is correct. If you modify

    hibernate.cfg.xml

    , be
    sure to clean the project before rebuilding.
  • If the application throws

    java.lang.ExceptionInInitializerError
    HibernateTravelPOJO.HibernateUtil

    , ensure that the
    database is running. If you are deploying to the Tomcat
    server, make sure that you added the

    jta.jar

    to the Hibernate322 library.
  • If the table component does not display new data when you select
    a different person from the drop-down list, open the Design View on
    Page1, and verify that you selected the Auto-Submit on Change item
    from the pop-up menu for the Drop Down List component.
  • If the application throws

    java.lang.reflect.UndeclaredThrowableException
    at $Proxy64.createQuery(Unknown Source)

    , make sure that you
    have included the antlr-2.7.6 library and not the antlr-1.6.5 library.

See Also:

This page was last modified: May 24,

Creating a Maven Swing Application Using Hibernate – NetBeans IDE Tutorial

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Configuring Maven
  • Creating the Maven Application
  • Adding Hibernate Files and Dependencies
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the Application GUI
  • Creating the Query in the HQL Query Editor
  • Adding the Query to the Form
  • Running a Maven Project
  • Creating POJOs and Mapping Files Individually

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.

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

version 2.09 or newer

version 5.x

Sakila Database

plugin available from update center

Before starting this tutorial you may want to familiarize yourself with the following documentation.

  • Hibernate documentation at hibernate.org

You can download a zip archive of the finished project.

Hibernate example in netbeans
Hibernate example in netbeans

Running the Project

The basics of the application are now complete. You can now run the application to check if everything is working correctly.

  1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL

http://localhost:8080/DVDStore/

that displays the list of films.

  1. In your browser, click “View” to load


    browse.xhtml

    to view the film details.

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.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/javaee/DVDStoreEE6. Click OK.

      3. Specify the Local Folder for the sources.

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Notes. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Troubleshooting

Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, you might want to look at the Troubleshooting section of the Creating a Simple Web Application Using a MySQL Database tutorial or the Connecting to a MySQL Database tutorial.

If you download and run the solution project you might see the following error in the Output window if it is the first time that you have deployed an application that uses the MySQL database.


SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org

In your browser window you might see a

java.lang.ExceptionInInitializerError

and the following stack trace.


java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.

(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ...

The output message states that the JDBC driver for the MySQL database was not found. The most probable reason is that you need to add the MySQL JDBC driver file to your GlassFish server installation. To confirm that the driver is missing, navigate to the

GLASSFISH-INSTALL/glassfish/domains/domain1/lib

directory on your local system (where GLASSFISH-INSTALL is your GlassFish installation directory). If the

domain1/lib

directory does not contain the JDBC driver file (for example,

mysql-connector-java-5.1.13-bin.jar

) you need to copy the JDBC driver to the directory. The MySQL JDBC driver is not added to your GlassFish installation when you install the server.

You can add a copy of the MySQL JDBC driver to your GlassFish installation by performing the following steps.

  1. Download the MySQL Connector/J JDBC driver.

  2. Extract the driver and copy the driver file (for example,


    mysql-connector-java-5.1.13-bin.jar

    ) to the

    domain1/lib

    directory of your GlassFish installation.

Alternatively, when you use the IDE to create an application that uses the MySQL database, the IDE can automatically copy the bundled MySQL JDBC driver to the GlassFish server when you deploy the project, if required. To confirm that the IDE will copy the necessary JDBC drivers, choose Tools > Servers from the main menu to open the Servers manager and confirm that the Enable JDBC Driver Deployment option is selected for your GlassFish server.

After you create and deploy a web application that uses the MySQL database, if you navigate to the

domain1/lib

directory of your local GlassFish installation you will see that directory contains the JDBC driver file.

Using Hibernate in a Java Swing Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Java Swing Application Project
  • Adding Hibernate Support to the Project
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the Application GUI
  • Creating the Query in the HQL Query Editor
  • Adding the Query to the Form
  • Running the Project
  • Creating POJOs and Mapping Files Individually
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a Java Swing application that displays data from a database. The application uses the Hibernate framework as the persistence layer to retrieve POJOs (plain old Java objects) from a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates the support for the Hibernate framework included in the IDE and how to use wizards to create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a GUI interface for searching and displaying the data.

The application that you build in this tutorial is a companion administration application for the DVD Store web application. This tutorial covers how to create an application that allows you to query an actor’s profile based on the match with first name or last name. If you wish you can extend the application to query film details and to add/update/delete items. This tutorial uses MySQL and the Sakila database, but you can use any supported database server with Hibernate applications. The Sakila database is a sample database that you can download from the MySQL site. Information for setting up the Sakila DB is provided in the following sections.

Before starting this tutorial you may want to familiarize yourself with the following documentation.

  • Hibernate documentation at hibernate.org.

  • Connecting to a MySQL Database tutorial.

To build this application using Maven, see Creating a Maven Swing Application Using Hibernate.

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.2, 7.3, 7.4, 8.0, Java

version 7 or 8

version 5.x

Sakila Database

plugin available from update center

You can download a zip archive of the finished project.

Hibernate and the NetBeans Visual Web Pack

Hibernate is an open source tool that provides object/relational persistence and query services. Hibernate sits between your application and database, and seamlessly loads and saves objects, assisting you with persistence content management.

This tutorial shows you how to build a Visual Web application that uses Hibernate libraries and plain old Java objects (POJOs). This tutorial is for developers who have a solid working knowledge of Hibernate. To learn more about Hibernate, see the Hibernate reference documentation.

In this tutorial, you wrap a Person POJO with an array of

model.Option

objects and bind a DropDown List component to the array. You then extend the

ObjectListDataProvider

class to build a

TripDataProvider

wrapper for the Trips POJO, and bind the Table component to an instance of the

TripDataProvider

class.

Note:
To learn more about the

model.Option

class, see Using List Components.

In this tutorial, you perform the following steps. These steps show the recommended method for building a Visual Web application that uses the Hibernate framework.

  1. Use the Library Manager tool to make the required Hibernate libraries available to the IDE. Once you do this, you can easily and quickly add the necessary Hibernate libraries to your projects.
  2. Create a Java Class Library project (POJO project) that segregates the Hibernate persistence code for the database tables into a reusable Hibernate front end.
  3. Add the database driver and the required Hibernate libraries to the POJO project.
  4. Develop a Visual Web Application project that references the POJO project and the Hibernate libraries.
  5. Use wrapper classes to connect the components to the Hibernate persistence classes.
Spring - Hibernate: step by step in netbeans
Spring – Hibernate: step by step in netbeans

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

configure()

and 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 dvdrental for the package. Click Finish.

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.

Notes.

  • 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.

Creating the Reverse Engineering File

The reverse engineering file (

hibernate.reveng.xml

) is an XML file that can be used to modify the default settings used when generating Hibernate files from the metadata of the database specified in

hibernate.cfg.xml

. The wizard generates the file with basic default settings. You can modify the file to explicitly specify the database schema that is used, to filter out tables that should not be used and to specify how JDBC types are mapped to Hibernate types.

  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. Keep the default *


    src

    * 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.

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.

When you click Finish, the IDE generates the POJO

Actor.java

with all the required fields and generates a Hibernate mapping file 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.

Hibernate  CRUD Project Step by Step
Hibernate CRUD Project Step by Step

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.

  2. Expand the

    source package 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 () in the toolbar.

When you click Run HQL Query you should see the query results in the bottom pane of the HQL Query Editor.

  1. 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%' )

  1. 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.

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a POJO (plain old Java object) to represent the data in each of the tables in the database that you will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables you can use a Hibernate mapping file or use annotations in the class.

You can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When you use the wizard you select all the tables for which you want POJOs and mapping files and the IDE then generates the files for you based on the database tables and 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).

Note. The IDE also has wizards to help you create individual POJOs and mapping files from scratch.

Creating the Hibernate Reverse Engineering File

If you want to use the Hibernate Mapping Files and POJOs from a Database wizard, you first need to create a

hibernate.reveng.xml

reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires

hibernate.reveng.xml

and

hibernate.cfg.xml

.

The reverse engineering file enables you to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that you can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.

  3. Specify


    hibernate.reveng

    as the File Name and

    src/java

    for the Folder. Click Next.

  4. Select


    hibernate.cfg.xml

    from the Configuration File drop down list, if not selected.

  5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

    • actor

    • category

    • film

    • film_actor

    • film_category

    • language

Click Finish.

The wizard generates a

hibernate.reveng.xml

reverse engineering file and opens the file in the editor. You can close the reverse engineering file because you will not need to edit the file.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Controlling reverse engineering in the Hibernate Tools Reference Guide.

Creating the Hibernate Mapping Files and POJOs

You can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for you. The wizard can generate a POJO and a corresponding mapping file for each table that you select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. You need to have the

hibernate.reveng.xml

and

hibernate.cfg.xml

files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

  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. Ensure that the


    hibernate.cfg.xml

    and

    hibernate.reveng.xml

    files are selected in the drop down lists.

  4. Select JDK 5 Language Features under the General Settings options.

  5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.

  6. Select dvdrental for the Package name. Click Finish.

When you click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in

hibernate.reveng.xml

. The IDE also adds mapping entries to

hibernate.cfg.xml

.



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory

Note. Confirm that the

mapping

elements are listed after the

property

elements in the

hibernate.cfg.xml

file.

You can expand the

dvdrental

package to see the files generated by the wizard.

You can use the Hibernate Mapping wizard if you want to create a Hibernate mapping file that maps a specific table to a specific class.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Basic O/R Mapping in the Hibernate Reference Documentation.

Simple CRUD Part 1: Hibernate Setup in NetBeans 8.2 - Create
Simple CRUD Part 1: Hibernate Setup in NetBeans 8.2 – Create

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;* }

  1. 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.

  2. In the Generate Getters and Setters dialog box, select all the fields and click Generate.

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.

  1. 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.

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:

  1. Map the fields in


    Actor.java

    to the columns in the ACTOR table by making the following changes (in bold) to

    Actor.hbm.xml

    .

You can use code completion in the editor to complete the values when modifying the mapping file.

By default, the generated
  1. 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.

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category and click Next.

Type DVDStore for the project name and set the project location if needed.

De-select the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

Set the server to GlassFish v3 and set the Java EE Version to Java EE 6 Web. Click Next.

Select the JavaServer Faces checkbox and use the default JSF 2.0 libraries.

Select the Hibernate 3.2.5 checkbox.

Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the hibernate.cfg.xml file and index.xhtml in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

———————————————————————

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the hibernate.cfg.xml configuration file at the root of the context classpath of the application (in the Files window, src/java). The file is located in the

under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in hibernate.cfg.xml to enable debug logging for SQL statements and to enable Hibernate’s session context management.

Open hibernate.cfg.xml in the Design tab. You can open the file by expanding Source Packages >

in the Projects window and double-clicking hibernate.cfg.xml.

In the multi-view XML editor, expand the Configuration Properties node under Optional Properties.

Click Add to open the Add Hibernate Property dialog box.

In the dialog box, select the hibernate.show_sql property and set the value to true. This enables the debug logging of the SQL statements.

Expand the Miscellaneous Properties node and click Add.

In the dialog box, select the properties hibernate.current_session_context_class and set the value to thread to enable Hibernate’s automatic session context management.

If you click the XML tab in the editor you can see the file in XML view. Your file should look like the following:

org.hibernate.dialect.MySQLDialect

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/sakila

root

######

true

thread

Save your changes to the file.

You can close the file because you do not need to edit the file again.

Java, ORM & Hibernate 1 | Back to Main | Java, ORM & Hibernate 3

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.

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.

  1. 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.

Hibernate First Program using NetBeans IDE and Oracle
Hibernate First Program using NetBeans IDE and Oracle

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the

hibernate.cfg.xml

configuration file at the root of the context classpath of the application (in the Files window,

src/java

). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in

hibernate.cfg.xml

to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open


    hibernate.cfg.xml

    in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking

    hibernate.cfg.xml

    .

  2. In the multi-view XML editor, 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

    . This enables the debug logging of the SQL statements.

  1. Expand the Miscellaneous Properties node and click Add.

  2. In the dialog box, select the


    properties hibernate.current_session_context_class

    and set the value to

    thread

    to enable Hibernate’s automatic session context management.

  1. Click Add again under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

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 (the three new properties are bold):



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### * true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *


  1. Save your changes to the file.

You can close the file because you do not need to edit the file again.

Creating the FilmHelper.java Helper Class

You will now create a helper class in the

dvdrental

package that will be used to perform Hibernate queries on the database. You will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After you test the queries you will create methods in the helper class that construct and run the queries. You will then invoke the methods in the helper class from a JSF managed bean.

Creating the Class

In this section you use the New File wizard to create the helper class

FilmHelper.java

in the

dvdrental

package. You will create a Hibernate session by calling

getSessionFactory

in

HibernateUtil.java

and create some helper methods to create queries to retrieve data from the database. You will invoke the helper methods from the JSP pages.

  1. Right-click the


    dvdrental

    source package node and select New > Java Class to open the New File wizard.

  2. Type FilmHelper for the class name.

  3. Confirm that dvdrental is selected as the Package. Click Finish.

  4. Adding the following code (in bold) to create a Hibernate session.


public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* }

  1. Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add any required import statements (


    org.hibernate.Session

    ) and save your changes.

You will now modify

FilmHelper.java

to add methods that query the DB.

Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise you will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. You will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the

filmId

primary key. You will use the HQL editor to construct and test the HQL query. After you have created the correct query you will add a method to the class that can generate the proper query.

  1. Right-click the project node in the Projects window and choose Clean and Build.

  2. Right-click


    hibernate.cfg.xml

    in the Projects window and choose Run HQL Query to open the HQL query editor.

  3. Select hibernate.cfg from the drop down list in the toolbar.

  4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( images:./run_hql_query_16.png[title=”Run HQL Query button”] ) in the toolbar.


from Film

When you click Run HQL Query you can see the results of the query in the bottom window of the HQL query editor.

If you click the SQL button you can see the equivalent SQL query.


select film0_.film_id as col_0_0_ from sakila.film film0_

  1. Type the following query to retrieve the records in the Film table where the film id is between 100 and 200.


from Film as film where film.filmId between 100 and 200

The result window displays a list of records. Now that you have tested that the query returns the desired results, you can use the query in the helper class.

  1. Add the following method


    getFilmTitles

    to

    FilmHelper.java

    to retrieve the films where the film id is between a certain range specified by the variables

    startID

    and

    endID

    .


public List getFilmTitles(int startID, int endID) { List

filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'"); filmList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; }


  1. Add the following method


    getActorsByID

    that retrieves the actors in a particular film. The method constructs the query using

    filmId

    as the input variable.


public List getActorsByID(int filmId){ List

actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')"); actorList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; }


  1. Fix your imports and save your changes.

When you fix your imports you want to choose

java.util.List

and

org.hibernate.Query

.

Adding Additional Helper Methods

You will now add additional helper methods that create queries based on an input variable. You can check the queries in the HQL query editor.

  1. Add the following method to retrieve a list of categories according to


    filmId

    .


public Category getCategoryByID(int filmId){ List

categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')"); categoryList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }


  1. Add the following method to retrieve a single film according to


    filmId

    .


public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Film as film where film.filmId=" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; }

  1. Add the following method to retrieve the film language according to


    langId

    .


public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Language as lang where lang.languageId=" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); }

  1. Save your changes.

Java Hibernate JPA: #8 LOG IN | Apache Netbeans
Java Hibernate JPA: #8 LOG IN | Apache Netbeans

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;* }

  1. Right-click in the editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Getter and Setter in the popup menu to generate getters and setters for the fields.

  2. In the Generate Getters and Setters dialog box, select all the fields and click Generate.

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.

  1. 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 check that the Folder is src/sakila/entity. Click Next.

  4. Type sakila.entity.Actor for the Class to Map and select actor from the Database Table drop down list. Click Finish.

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:

  1. Map the fields in


    Actor.java

    to the columns in the ACTOR table by making the following changes (in bold) to

    Actor.hbm.xml

    .

You can use code completion in the editor to complete the values when modifying the mapping file.

By default, the generated
  1. 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 customizing your application.

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the

hibernate.cfg.xml

configuration file at the root of the context classpath of the application (in the Files window,

src/java

). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in

hibernate.cfg.xml

to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open


    hibernate.cfg.xml

    in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking

    hibernate.cfg.xml

    .

  2. In the multi-view XML editor, 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

    . This enables the debug logging of the SQL statements.

  1. Expand the Miscellaneous Properties node and click Add.

  2. In the dialog box, select the


    properties hibernate.current_session_context_class

    and set the value to

    thread

    to enable Hibernate’s automatic session context management.

  1. Click Add again under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

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 (the three new properties are bold):



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### * true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *


  1. Save your changes to the file.

You can close the file because you do not need to edit the file again.

Hibernate Create, Read, Update and Delete (CRUD) Operations Example
Hibernate Create, Read, Update and Delete (CRUD) Operations Example

Creating the JSF Managed Bean

In this exercise you will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables you to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the


    dvdrental

    source package node and choose New > Other.

  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.

  3. Type FilmController for the Class Name.

You will use the Managed Bean name

filmController

as the value for the

inputText

and

commandButton

in the JSF page

index.xhtml

when calling methods in the bean.

  1. Select dvdrental for the Package.

  2. Type filmController for the Name that will be used for the managed bean.

  3. Set Scope to Session. Click Finish.

When you click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the

@ManagedBean

and

@SessionScoped

annotations.


@ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } }

Note. Note that the name of the managed bean is not explicitly specified. By default, the name of the bean is the same as the class name and begins with a lower-case letter. If you want the name of the bean to be different from the class name, you can explicitly specify the name as a parameter of the

@ManagedBean

annotations (for example,

@ManagedBean(name="myBeanName")

.

  1. Add the following fields (in bold) to the class.


@ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* }

  1. Add the following code (in bold) to create the FilmController instance and retrieve the films.


/** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }*

  1. Add the following methods that are used to display the table and navigate the pages.* public boolean isHasNextPage() { if (endId + pageSize ⇐ recordCount) { return true; } return false; }

    public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; }

    public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return “index”; }

    public String previous() { startId = startId – pageSize; endId = endId – pageSize; recreateModel(); return “index”; }

    public int getPageSize() { return pageSize; }

    public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return “browse”; } public String prepareList(){ recreateModel(); return “index”; } *

The methods that return “index” or “browse” will prompt the JSF navigation handler to try to open a page named

index.xhtml

or

browse.xhtml

. The JSF 2.0 specification enables the use of implicit navigation rules in applications that use Facelets technology. In this application, no navigation rules are configured in

faces-config.xml

. Instead, the navigation handler will try to locate a suitable page in the application.

  1. Add the following methods that access the helper class to retrieve additional film details.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; }

    public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append(” “); totalCast.append(actor.getLastName()); totalCast.append(” “); } return totalCast.toString(); }

    public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }*

  1. Fix your imports (Ctrl-Shift-I) and save your changes.

You can use the code completion in the editor to help you type your code.

Preparing the Hibernate Front End to the Database

It is good practice to segregate the Hibernate code that accesses the database into a separate project. The

HibernateTravelPOJO.zip

file contains the HibernateTravelPOJO project, which is a Hibernate front end for accessing the
Travel database.
You can import HibernateTravelPOJO as a library dependency into any
Visual Web project to enable that project to access the Travel database through Hibernate’s mappings. The HibernateTravelPOJO project contains the required mapping file, configuration file, utility class, and POJO persistent classes, as described in Introduction to Hibernate. The following figure shows the project’s contents.

Figure 2: Contents of the HibernateTravelPOJO Project

Note: For simplicity, the HibernateTravelPOJO is a subset of a full front end for the Travel database and only contains the classes, properties, and relationships that are necessary for the tutorial project.

  1. Extract the contents of the
    HibernateTravelPOJO.zip file into the

    NetBeansProjects

    folder under your home directory, or into directory of your choice.
  2. In the IDE, close any open projects.
  3. Choose File > Open Project, and open the HibernateTravelPOJO project.
  4. In the Projects window, expand the HibernateTravelPOJO node, right-click the Libraries node, and choose Add Library from the pop-up menu.
  5. In the Add Library dialog box, select Hibernate322 and click Add Library.
  6. Right-click the Libraries node again, and choose Add JAR/Folder from the pop-up menu.
  7. Navigate to and select the JavaDB network client

    derbyclient.jar

    for the Travel database’s server. With a typical Visual
    Web Pack installation,
    this JAR file is in
    Sun-Java-Application-Server-Install-Dir

    /javadb/lib/derbyclient.jar

    If you are using a different database server, navigate to and
    select that server’s client.

  8. Press Enter.

    The database driver is now available for Hibernate connections to the database.

  9. If you are using a different port number than the default port number of 1527, or if you are using a different database, edit the

    hibernate.connection.url

    property in the HibernateTravelPOJO > Source Packages > default packages >

    hibernate.cfg.xml

    configuration file.

    To determine the port number for your database, look in the
    Runtime window for the jdbc node for the Travel database.
    The port number follows the host name.
    If the Travel database is not available, see the Configuration Information section in the NetBeans Visual Web Pack Installation Instructions for information.

  10. In the Projects window, right-click the HibernateTravelPOJO node and choose Build Project.
Cách để tạo Project Hibernate với NetBeans bản mới nhất & generate entity từ DB sử dụng SQL Server.
Cách để tạo Project Hibernate với NetBeans bản mới nhất & generate entity từ DB sử dụng SQL Server.

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.

When you click OK a Sakila node appears under the MySQL Server node.

  1. 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.

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.

  1. Type DVDStoreAdmin for the project name and set the project location.

  2. 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.

  1. 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.

Hibernate Tutorial For Beginners | Java Hibernate in 100 minutes | Hibernate Project | Simplilearn
Hibernate Tutorial For Beginners | Java Hibernate in 100 minutes | Hibernate Project | Simplilearn

See Also

For additional information on creating Swing GUI applications, see the following tutorials.

Let’s assume we need a small database application that can store events we want to attend, and information about the host(s) of these events. We will use an in-memory, Java database named HSQLDB to avoid describing installation/setup of any particular database servers. Feel free to tweak this tutorial to use whatever database you feel comfortable using.

The first thing we need to do is set up our development environment,
and specifically to setup all the required dependencies to Hibernate
as well as other libraries. Hibernate is built using Maven which
amongst other features provides

dependecy management

;
moreover it provides transitive

dependecy management

which simply means that to use
Hibernate we can simply define our dependency on Hibernate, Hibernate
itself defines the dependencies it needs which then become transitive
dependencies of our project.

.



${groupId}


hibernate-core





javax.servlet


servlet-api


Essentially we are describing here the

/tutorials/web/pom.xml

file. See the
Maven site for more information.

While not strictly necessary, most IDEs have integration with Maven to read these POM files and automatically set up a project for you which can save lots of time and effort.

Next we create a class that represents the event we want to store in database.

Our first persistent class is a simple JavaBean class with some properties:

package org.hibernate.tutorial.domain; import java.util.Date; public class Event { private Long id; private String title; private Date date; public Event() {} public Long getId() { return id; } private void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }

You can see that this class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields. This is a recommended design – but not required. Hibernate can also access fields directly, the benefit of accessor methods is robustness for refactoring. The no-argument constructor is required to instantiate an object of this class through reflection.

The

id

property holds a unique identifier value for a particular event.
All persistent entity classes (there are less important dependent classes as well) will need
such an identifier property if we want to use the full feature set of Hibernate. In fact,
most applications (esp. web applications) need to distinguish objects by identifier, so you
should consider this a feature rather than a limitation. However, we usually don’t manipulate
the identity of an object, hence the setter method should be private. Only Hibernate will assign
identifiers when an object is saved. You can see that Hibernate can access public, private,
and protected accessor methods, as well as (public, private, protected) fields directly. The
choice is up to you and you can match it to fit your application design.

The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you, using Java Reflection. The constructor can be private, however, package visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.

Place this Java source file in a directory called

src

in the
development folder, and in its correct package. The directory should now look like this:

. +lib

+src +events Event.java

In the next step, we tell Hibernate about this persistent class.

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

The basic structure of a mapping file looks like this:



[…]

Note that the Hibernate DTD is very sophisticated. You can use it for
auto-completion of XML mapping elements and attributes in your editor or
IDE. You also should open up the DTD file in your text editor – it’s the
easiest way to get an overview of all elements and attributes and to see
the defaults, as well as some comments. Note that Hibernate will not
load the DTD file from the web, but first look it up from the classpath
of the application. The DTD file is included in

hibernate3.jar

as well as in the

src/

directory of the Hibernate distribution.

We will omit the DTD declaration in future examples to shorten the code. It is of course not optional.

Between the two

hibernate-mapping

tags, include a

class

element. All persistent entity classes (again, there
might be dependent classes later on, which are not first-class entities) need
such a mapping, to a table in the SQL database:

So far we told Hibernate how to persist and load object of class

Event

to the table

EVENTS

, each instance represented by a row in that table.
Now we continue with a mapping of the unique identifier property to the tables primary key.
In addition, as we don’t want to care about handling this identifier, we configure Hibernate’s
identifier generation strategy for a surrogate primary key column:

The

id

element is the declaration of the identifier property,

name="id"

declares the name of the Java property –
Hibernate will use the getter and setter methods to access the property.
The column attribute tells Hibernate which column of the

EVENTS

table we use for this primary key. The nested

generator

element specifies the identifier generation strategy,
in this case we used

native

, which picks the best strategy depending
on the configured database (dialect). Hibernate supports database generated, globally
unique, as well as application assigned identifiers (or any strategy you have written
an extension for).

Finally we include declarations for the persistent properties of the class in the mapping file. By default, no properties of the class are considered persistent:

Just as with the

id

element, the

name

attribute of the

property

element tells Hibernate which getter
and setter methods to use. So, in this case, Hibernate will look for

getDate()/setDate()

, as well as

getTitle()/setTitle()

.

Why does the

date

property mapping include the

column

attribute, but the

title

doesn’t? Without the

column

attribute Hibernate
by default uses the property name as the column name. This works fine for

title

. However,

date

is a reserved
keyword in most database, so we better map it to a different name.

The next interesting thing is that the

title

mapping also lacks
a

type

attribute. The types we declare and use in the mapping
files are not, as you might expect, Java data types. They are also not SQL
database types. These types are so called Hibernate mapping types,
converters which can translate from Java to SQL data types and vice versa. Again,
Hibernate will try to determine the correct conversion and mapping type itself if
the

type

attribute is not present in the mapping. In some cases this
automatic detection (using Reflection on the Java class) might not have the default you
expect or need. This is the case with the

date

property. Hibernate can’t
know if the property (which is of

java.util.Date

) should map to a
SQL

date

,

timestamp

, or

time

column.
We preserve full date and time information by mapping the property with a

timestamp

converter.

This mapping file should be saved as

Event.hbm.xml

, right in
the directory next to the

Event

Java class source file.
The naming of mapping files can be arbitrary, however the

hbm.xml

suffix is a convention in the Hibernate developer community. The directory structure
should now look like this:

. +lib

+src +events Event.java Event.hbm.xml

We continue with the main configuration of Hibernate.

We now have a persistent class and its mapping file in place. It is time to configure
Hibernate. Before we do this, we will need a database. HSQL DB, a java-based SQL DBMS,
can be downloaded from the HSQL DB website(http://hsqldb.org/). Actually, you only need the

hsqldb.jar

from this download. Place this file in the

lib/

directory of the
development folder.

Create a directory called

data

in the root of the development directory –
this is where HSQL DB will store its data files. Now start the database by running

java -classpath ../lib/hsqldb.jar org.hsqldb.Server

in this data directory.
You can see it start up and bind to a TCP/IP socket, this is where our application
will connect later. If you want to start with a fresh database during this tutorial,
shutdown HSQL DB (press

CTRL + C

in the window), delete all files in the

data/

directory, and start HSQL DB again.

Hibernate is the layer in your application which connects to this database, so it needs connection information. The connections are made through a JDBC connection pool, which we also have to configure. The Hibernate distribution contains several open source JDBC connection pooling tools, but will use the Hibernate built-in connection pool for this tutorial. Note that you have to copy the required library into your classpath and use different connection pooling settings if you want to use a production-quality third party JDBC pooling software.

For Hibernate’s configuration, we can use a simple

hibernate.properties

file, a
slightly more sophisticated

hibernate.cfg.xml

file, or even complete
programmatic setup. Most users prefer the XML configuration file:




org.hsqldb.jdbcDriver jdbc:hsqldb:hsql://localhost sa
org.hibernate.dialect.HSQLDialect thread org.hibernate.cache.NoCacheProvider true create

Note that this XML configuration uses a different DTD. We configure
Hibernate’s

SessionFactory

– a global factory responsible
for a particular database. If you have several databases, use several
configurations, usually in
several configuration files (for easier startup).

The first four

property

elements contain the necessary
configuration for the JDBC connection. The dialect

property

element specifies the particular SQL variant Hibernate generates.
Hibernate’s automatic session management for persistence contexts will
come in handy as you will soon see.
The

hbm2ddl.auto

option turns on automatic generation of
database schemas – directly into the database. This can of course also be turned
off (by removing the config option) or redirected to a file with the help of
the

SchemaExport

Ant task. Finally, we add the mapping file(s)
for persistent classes to the configuration.

Copy this file into the source directory, so it will end up in the
root of the classpath. Hibernate automatically looks for a file called

hibernate.cfg.xml

in the root of the classpath, on startup.

We’ll now build the tutorial with Ant. You will need to have Ant installed – get
it from the Ant download page.
How to install Ant will not be covered here. Please refer to the
Ant manual. After you
have installed Ant, we can start to create the buildfile. It will be called

build.xml

and placed directly in the development directory.

A basic build file looks like this:

This will tell Ant to add all files in the lib directory ending with

.jar

to the classpath used for compilation. It will also copy all non-Java source files to the
target directory, e.g. configuration and Hibernate mapping files. If you now run Ant, you
should get this output:

C:\hibernateTutorial\>ant Buildfile: build.xml copy-resources: [copy] Copying 2 files to C:\hibernateTutorial\bin compile: [javac] Compiling 1 source file to C:\hibernateTutorial\bin BUILD SUCCESSFUL Total time: 1 second

It’s time to load and store some

Event

objects, but first
we have to complete the setup with some infrastructure code. We have to startup
Hibernate. This startup includes building a global

SessionFactory

object and to store it somewhere for easy access in application code.
A

SessionFactory

can open up new

Session

‘s.
A

Session

represents a single-threaded unit of work, the

SessionFactory

is a thread-safe global object, instantiated once.

We’ll create a

HibernateUtil

helper class which takes care
of startup and makes accessing a

SessionFactory

convenient.
Let’s have a look at the implementation:

package util; import org.hibernate.*; import org.hibernate.cfg.*; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println(“Initial SessionFactory creation failed.” + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }

This class does not only produce the global

SessionFactory

in
its static initializer (called once by the JVM when the class is loaded), but also
hides the fact that it uses a static singleton. It might as well lookup the

SessionFactory

from JNDI in an application server.

If you give the

SessionFactory

a name in your configuration
file, Hibernate will in fact try to bind it to JNDI after it has been built.
To avoid this code completely you could also use JMX deployment and let the
JMX-capable container instantiate and bind a

HibernateService

to JNDI. These advanced options are discussed in the Hibernate reference
documentation.

Place

HibernateUtil.java

in the development source directory, in
a package next to

events

:

. +lib

+src +events Event.java Event.hbm.xml +util HibernateUtil.java hibernate.cfg.xml +data build.xml

This should again compile without problems. We finally need to configure a logging
system – Hibernate uses commons logging and leaves you the choice between Log4j and
JDK 1.4 logging. Most developers prefer Log4j: copy

log4j.properties

from the Hibernate distribution (it’s in the

etc/

directory) to
your

src

directory, next to

hibernate.cfg.xml

.
Have a look at the example configuration and change the settings if you like to have
more verbose output. By default, only Hibernate startup message are shown on stdout.

The tutorial infrastructure is complete – and we are ready to do some real work with Hibernate.

Finally, we can use Hibernate to load and store objects. We write an

EventManager

class with a

main()

method:

package events; import org.hibernate.Session; import java.util.Date; import util.HibernateUtil; public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); if (args[0].equals(“store”)) { mgr.createAndStoreEvent(“My Event”, new Date()); } HibernateUtil.getSessionFactory().close(); } private void createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); } }

We create a new

Event

object, and hand it over to Hibernate.
Hibernate now takes care of the SQL and executes

INSERT

s
on the database. Let’s have a look at the

Session

and

Transaction

-handling code before we run this.

A

Session

is a single unit of work. For now we’ll keep things
simple and assume a one-to-one granularity between a Hibernate

Session

and a database transaction. To shield our code from the actual underlying transaction
system (in this case plain JDBC, but it could also run with JTA) we use the

Transaction

API that is available on the Hibernate

Session

.

What does

sessionFactory.getCurrentSession()

do? First, you can call it
as many times and anywhere you like, once you get hold of your

SessionFactory

(easy thanks to

HibernateUtil

). The

getCurrentSession()

method always returns the “current” unit of work. Remember that we switched the configuration
option for this mechanism to “thread” in

hibernate.cfg.xml

? Hence,
the current unit of work is bound to the current Java thread that executes our application.
However, this is not the full picture, you also have to consider scope, when a unit of work
begins and when it ends.

A

Session

begins when it is first needed, when the first call to

getCurrentSession()

is made. It is then bound by Hibernate to the current
thread. When the transaction ends, either through commit or rollback, Hibernate automatically
unbinds the

Session

from the thread and closes it for you. If you call

getCurrentSession()

again, you get a new

Session

and can
start a new unit of work. This thread-bound programming model is the most
popular way of using Hibernate, as it allows flexible layering of your code (transaction
demarcation code can be separated from data access code, we’ll do this later in this tutorial).

Related to the unit of work scope, should the Hibernate

Session

be used to
execute one or several database operations? The above example uses one

Session

for one operation. This is pure coincidence, the example is just not complex enough to show any
other approach. The scope of a Hibernate

Session

is flexible but you should
never design your application to use a new Hibernate

Session

for
every database operation. So even if you see it a few more times in
the following (very trivial) examples, consider session-per-operation
an anti-pattern. A real (web) application is shown later in this tutorial.

Have a look at Chapter 11, Transactions And Concurrency for more information about transaction handling and demarcation. We also skipped any error handling and rollback in the previous example.

To run this first routine we have to add a callable target to the Ant build file:

The value of the

action

argument is set on the command line when
calling the target:

C:\hibernateTutorial\>ant run -Daction=store

You should see, after compilation, Hibernate starting up and, depending on your configuration, lots of log output. At the end you will find the following line:

[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)

This is the

INSERT

executed by Hibernate, the question marks
represent JDBC bind parameters. To see the values bound as arguments, or to reduce
the verbosity of the log, check your

log4j.properties

.

Now we’d like to list stored events as well, so we add an option to the main method:

if (args[0].equals(“store”)) { mgr.createAndStoreEvent(“My Event”, new Date()); } else if (args[0].equals(“list”)) { List events = mgr.listEvents(); for (int i = 0; i < events.size(); i++) { Event theEvent = (Event) events.get(i); System.out.println(“Event: ” + theEvent.getTitle() + ” Time: ” + theEvent.getDate()); } }

We also add a new

listEvents() method

:

private List listEvents() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List result = session.createQuery(“from Event”).list(); session.getTransaction().commit(); return result; }

What we do here is use an HQL (Hibernate Query Language) query to load all existing

Event

objects from the database. Hibernate will generate the
appropriate SQL, send it to the database and populate

Event

objects
with the data. You can create more complex queries with HQL, of course.

Now, to execute and test all of this, follow these steps:

Run

ant run -Daction=store

to store something into the database
and, of course, to generate the database schema before through hbm2ddl.

Now disable hbm2ddl by commenting out the property in your

hibernate.cfg.xml

file. Usually you only leave it turned on in continuous unit testing, but another
run of hbm2ddl would drop everything you have stored – the

create

configuration setting actually translates into “drop all
tables from the schema, then re-create all tables, when the SessionFactory is build”.

If you now call Ant with

-Daction=list

, you should see the events
you have stored so far. You can of course also call the

store

action a few
times more.

Note: Most new Hibernate users fail at this point and we see questions about Table not found error messages regularly. However, if you follow the steps outlined above you will not have this problem, as hbm2ddl creates the database schema on the first run, and subsequent application restarts will use this schema. If you change the mapping and/or database schema, you have to re-enable hbm2ddl once again.

Messages:
File: org/apache/catalina/servlets/DefaultServlet.java
Line number: 868

org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:614) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

org.apache.tiles.servlet.context.ServletTilesRequestContext.wrapServletException(ServletTilesRequestContext.java:298) org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:200) org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:179) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:606) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:669) org.apache.jsp.mylayout_jsp._jspService(mylayout_jsp.java:638) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459) org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:385) org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198) org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:179) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:606) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:868) org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:519) javax.servlet.http.HttpServlet.service(HttpServlet.java:655) org.apache.catalina.servlets.DefaultServlet.service(DefaultServlet.java:499) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:578) org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:517) org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:994) org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:500) org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:80) org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:73) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:283) org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:140) org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:117) org.apache.tiles.jsp.taglib.RenderTagSupport.execute(RenderTagSupport.java:154) org.apache.tiles.jsp.taglib.RoleSecurityTagSupport.doEndTag(RoleSecurityTagSupport.java:75) org.apache.tiles.jsp.taglib.ContainerTagSupport.doEndTag(ContainerTagSupport.java:80) org.apache.jsp.mylayout_jsp._jspx_meth_tiles_005finsertAttribute_005f2(mylayout_jsp.java:875) org.apache.jsp.mylayout_jsp._jspService(mylayout_jsp.java:239) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459) org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:385) org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198) org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:179) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:606) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

You are seeing this page because development mode is enabled. Development mode, or devMode, enables extra debugging behaviors and reports to assist developers. To disable this mode, set:

struts.devMode=falsein your


WEB-INF/classes/struts.propertiesfile.

>> More Visual Web Pack Documentation

Using Hibernate With the NetBeans Visual Web Pack

Contributed by Chris
Kutler, Craig McClananan, and John Baker

May [Revision number: V5.5.1-1]

This tutorial shows you how to use the Hibernate framework in a NetBeans Visual Web Pack project. It also shows how to wrap
back end data with Option arrays and ObjectListDataProvider
objects for binding to JavaServer Faces components.

Examples used in this tutorial

» HibernateTravelPOJO.zip

This tutorial works with the following technologies and resources

JavaServer Faces Components/
Java EE Platform
1.2 with Java EE 5*1.1 with J2EE 1.4
Travel Database Required
BluePrints AJAX Component Library Not required

* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.

This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17.
If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds.
For detailed information about the
supported servers and Java EE platform, see the Release Notes.

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.

  1. Drag a Label element from the Palette and change the text to Last Name.

  2. Drag a Text Field element next to the Last Name label and delete the default text.

  3. Drag a Button element from the Palette and change the text to Query.

  4. Drag a Table element from the Palette into the form.

  5. 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.

Element Variable Name

First Name text field

Last Name text field

Query button

Table

  1. 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.

  1. Save your changes.

In Design view your form should look similar to the following image.

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.

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.

  1. 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.

  1. 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.

  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate import statements for the Hibernate libraries (


    org.hibernate.Query

    ,

    org.hibernate.Session

    ) and

    java.util.List

    . Save your changes.

  2. 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.

  1. 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(); }* }

  1. Add the following method to display the results in the JTable.


private void displayResult(List resultList) { Vector

tableHeaders = new Vector

(); 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
oneRow = new Vector
(); 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)); }



  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate an import statement for


    java.util.Vector

    and

    java.util.List

    . Save your changes.

After you save the form you can run the project.

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a POJO (plain old Java object) to represent the data in each of the tables in the database that you will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables you can use a Hibernate mapping file or use annotations in the class.

You can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When you use the wizard you select all the tables for which you want POJOs and mapping files and the IDE then generates the files for you based on the database tables and 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).

Note. The IDE also has wizards to help you create individual POJOs and mapping files from scratch.

Creating the Hibernate Reverse Engineering File

If you want to use the Hibernate Mapping Files and POJOs from a Database wizard, you first need to create a

hibernate.reveng.xml

reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires

hibernate.reveng.xml

and

hibernate.cfg.xml

.

The reverse engineering file enables you to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that you can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.

  3. Specify


    hibernate.reveng

    as the File Name and

    src/java

    for the Folder. Click Next.

  4. Select


    hibernate.cfg.xml

    from the Configuration File drop down list, if not selected.

  5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

    • actor

    • category

    • film

    • film_actor

    • film_category

    • language

Click Finish.

The wizard generates a

hibernate.reveng.xml

reverse engineering file and opens the file in the editor. You can close the reverse engineering file because you will not need to edit the file.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Controlling reverse engineering in the Hibernate Tools Reference Guide.

Creating the Hibernate Mapping Files and POJOs

You can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for you. The wizard can generate a POJO and a corresponding mapping file for each table that you select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. You need to have the

hibernate.reveng.xml

and

hibernate.cfg.xml

files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

  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. Ensure that the


    hibernate.cfg.xml

    and

    hibernate.reveng.xml

    files are selected in the drop down lists.

  4. Select JDK 5 Language Features under the General Settings options.

  5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.

  6. Select dvdrental for the Package name. Click Finish.

When you click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in

hibernate.reveng.xml

. The IDE also adds mapping entries to

hibernate.cfg.xml

.



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory

Note. Confirm that the

mapping

elements are listed after the

property

elements in the

hibernate.cfg.xml

file.

You can expand the

dvdrental

package to see the files generated by the wizard.

You can use the Hibernate Mapping wizard if you want to create a Hibernate mapping file that maps a specific table to a specific class.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Basic O/R Mapping in the Hibernate Reference Documentation.

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 left 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.

  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.

Element Variable Name

First Name text field

Last Name text field

Query button

Table

  1. Save your changes.

In Design view your form should look similar to the following image.

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.

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.

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).

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.

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.

  1. Click Add under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Type org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory in the text field. Click OK.

Note. Do not select the value from the drop-down list.

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:



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### true org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

  1. 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.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Web Application from the Java Web category and click Next.

  2. Type DVDStore for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

  1. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web or Java EE 7 Web. Click Next.

  2. Select the JavaServer Faces checkbox and use the default JSF 2.x libraries.

  3. Select the Hibernate checkbox in the list of frameworks.

  4. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the

hibernate.cfg.xml

file and

index.xhtml

in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

Using Hibernate in a Web Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Web Application Project
  • Modifying the Hibernate Configuration File
  • Creating the

    HibernateUtil.java

    Helper File
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the

    FilmHelper.java

    Helper Class
  • Creating the JSF Managed Bean
  • Creating the Web Pages
  • Running the Project
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a JSF managed bean and JSF 2.0 pages to display the data.

Before starting this tutorial you may want to familiarize yourself with the following documents.

  • Hibernate documentation at hibernate.org

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.1, 7.2, 7.3, 7.4, Java EE version

Version 6 or 7

GlassFish Server Open Source Edition

3.x or 4.x

Version 5.x

Sakila Database

Plugin available from update center

You can download a zip archive of the finished project.

How does Hibernate work?

Hibernate is an open source Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from most common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

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

configure()

and 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 dvdrental for the package. Click Finish.

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.

Notes.

  • 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.

Creating the Reverse Engineering File

The reverse engineering file (

hibernate.reveng.xml

) is an XML file that can be used to modify the default settings used when generating Hibernate files from the metadata of the database specified in

hibernate.cfg.xml

. The wizard generates the file with basic default settings. You can modify the file to explicitly specify the database schema that is used, to filter out tables that should not be used and to specify how JDBC types are mapped to Hibernate types.

  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. Keep the default *


    src

    * 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.

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.

When you click Finish, the IDE generates the POJO

Actor.java

with all the required fields and generates a Hibernate mapping file 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 Java Swing Application Project

In this exercise you create a simple Java Swing application project called DVDStoreAdmin.

  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category and click Next.

  2. Type DVDStoreAdmin for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

    1. Deselect Create Main Class. Click Finish.

When you click Finish, the IDE creates the Java application project. The project does not have a main class. You will create a form and then set the form as the main class.

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Web Application from the Java Web category and click Next.

  2. Type DVDStore for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

  1. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web or Java EE 7 Web. Click Next.

  2. Select the JavaServer Faces checkbox and use the default JSF 2.x libraries.

  3. Select the Hibernate checkbox in the list of frameworks.

  4. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the

hibernate.cfg.xml

file and

index.xhtml

in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

Creating the Java Swing Application Project

In this exercise you create a simple Java Swing application project called DVDStoreAdmin.

  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category and click Next.

  2. Type DVDStoreAdmin for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

    1. Deselect Create Main Class. Click Finish.

When you click Finish, the IDE creates the Java application project. The project does not have a main class. You will create a form and then set the form as the main class.

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.

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 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;* }

  1. Right-click in the editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Getter and Setter in the popup menu to generate getters and setters for the fields.

  2. In the Generate Getters and Setters dialog box, select all the fields and click Generate.

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.

  1. 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 check that the Folder is src/sakila/entity. Click Next.

  4. Type sakila.entity.Actor for the Class to Map and select actor from the Database Table drop down list. Click Finish.

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:

  1. Map the fields in


    Actor.java

    to the columns in the ACTOR table by making the following changes (in bold) to

    Actor.hbm.xml

    .

You can use code completion in the editor to complete the values when modifying the mapping file.

By default, the generated
  1. 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 customizing your application.

Keywords searched by users: hibernate example in netbeans

Working With Hibernate In Netbeans - Youtube
Working With Hibernate In Netbeans – Youtube
Netbeans Missing Hibernate Library - Miscellaneous - Hibernate
Netbeans Missing Hibernate Library – Miscellaneous – Hibernate
Hibernate Hello World Example With Mysql, Maven, And Eclipse - Youtube
Hibernate Hello World Example With Mysql, Maven, And Eclipse – Youtube
How To Perform Basic Sql Operation Using Hibernate In Netbeans -  Whatinfotech
How To Perform Basic Sql Operation Using Hibernate In Netbeans – Whatinfotech
Swing Crud Application With Hibernate And Sql Server On Netbeans - Youtube
Swing Crud Application With Hibernate And Sql Server On Netbeans – Youtube
Tutorial:Create Struts2 Hibernate Example Application In Eclipse
Tutorial:Create Struts2 Hibernate Example Application In Eclipse

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *