DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Wicket, JPA, GlassFish and Java Derby or MySQL

Wicket, JPA, GlassFish and Java Derby or MySQL

Carol McDonald user avatar by
Carol McDonald
·
Dec. 03, 09 · Interview
Like (1)
Save
Tweet
Share
21.85K Views

Join the DZone community and get the full member experience.

Join For Free

This Pet Catalog app explains a web application that uses Wicket, JPA, GlassFish and MySQL. I took this example JSF 2.0, JPA, GlassFish and MySQL  and modified it to use Wicket instead of JSF. 

  • Download the sample code

Explanation of the usage of Wicket, Java Persistence APIs, Glassfish and MySQL in a sample Store Catalog Application

The image below shows the Catalog Listing page, which allows a user to page through a list of items in a store.



The Wicket Framework

The Wicket Web Framework provides a component-oriented programmatic manipulation of HTML markup. The Diagram below shows how the Wicket Framework fits into the MVC design pattern.


A Wicket component controller receives user input. The component uses the user input to interact with the model, to handle page navigation and events. The Model provide components with an interface to domain data. The Component view renders the User Interface HTML elements. The controller and view parts are combined into the Component  in Wicket.


Wicket Triad of HTML Templates, Components, and Model

The Wicket component, the model, and HTML template work together. The HTML template defines the static parts of the pages, components fill in the dynamic parts, and models are used by components to get the domain data for the dynamic parts.  Wicket matches wicket:id tags with components, Models are a reference to the data for the Java components.

Wicket  HTML Templates

Wicket templates are written in plain HTML, consumable by standard HTML editors. Wicket uses HTML namespace standards to extend HTML with placeholders,  where Wicket components are hooked in, so that there is no custom syntax at all. Wicket matches wicket: id attributes and attaches Java components to the tags in which these attributes are defined.

Wicket Web pages are all Java classes that map to an HTML template, with the same name as the Java class.


The ListPage.html file holds the markup for the ListPage.java.  Wicket matches the Java page instance and the HTML template file with the same name in the same Java package.

<table>
<tr>
<th> Name </th>
<th> Photo</th>
<th> Price </th>
</tr>
<tr wicket:id="rows" >
<td>
<a wicket:id="details" href="#">
<span wicket:id="name">name</span>
</a>
</td>
<td> <img wicket:id="photo"/></td>
<td><span wicket:id="price"></span></td>

</tr>
</table>
<span wicket:id="pager">navigation controls here</span>

 Pages are special top-level components that hold the root for component trees. Below is the component tree for the ListPage above:


Wicket Components

Wicket matches the wicket:id="rows" attribute in the ListPage.html with the corresponing Java component in ListPage.java,  which is a DataViewComponent which has a DataProvider model as shown in the diagram below.



The corresponding ListPage.java code is shown below:

 

public class ListPage extends WebPage {

// create the Model DataProvider
IDataProvider itemDataProvider = new IDataProvider<Item>() {

public Iterator iterator(int first, int count) {
return itemController.findItemEntities(count, first).iterator();
}
public int size() {
return itemController.getItemCount();
}
public IModel model(final Item object) {
return new LoadableDetachableModel() {
@Override
protected Item load() {
return (Item) object;
}
};
}
public void detach() {
}
};

// create the DataView component corresponding to the wicketid "rows" attribute in ListPage.html
DataView dataView = new DataView<Item>("rows", itemDataProvider, ROWS_PER_PAGE) {

@Override
protected void populateItem(org.apache.wicket.markup.repeater.Item<Item> repItem) {
Item item = (Item) repItem.getModelObject();
repItem.setModel(new CompoundPropertyModel<Item>(item));
repItem.add(ItemDetails.link("details", item));
repItem.add(new Image("photo", new ResourceReference(this.getClass(), item.getImagethumburl())));
repItem.add(new Label("price"));

}
};
// add the DataView component to the page
add(dataView);
// create the PagingNavigator component corresponding to the "pager" attribute in ListPage.html
PagingNavigator pager = new PagingNavigator("pager", dataView);
add(pager);

DataView is a component which makes it simple to populate a Wicket RepeatingView from a database by utilizing IDataProvider to act as an interface between the database and the dataview.  A Wicket RepeatingView renders the components added to it from data from a collection of objects.

The  DataView instantiation passes to the constructor  the wicket id "rows" , the itemDataProvider, and the number of rows for paging, and anonymously overrides the populateItem() method, which will be called for each Item object provided by itemDataProvider.  The  populateItem method adds the child components ( Link, Image, Label)  with the Item  Model to the Dataview.


The itemDataProvider IDataProvider provides the Pet Catalog  Item data to the DataView.  The IDataProvider iterator(int first, int count) method gets an iterator for the subset of total data.  The itemDataProvider iterator method calls the  itemController.findItemEntities , which uses JPA to query the database and return a list of Item entities.  The itemDataProvider model method  is a Callback used by the consumer of this data provider to wrap objects retrieved from iterator(int, int) with a model (usually a detachable one).



Using the Java Persistence API (JPA) with Wicket

The ItemJpaController findItemEntities method is defined as shown below:

public class ItemJpaController {

public ItemJpaController() {
emf = Persistence.createEntityManagerFactory("wicketCatalogPU");
}
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
return emf.createEntityManager();
}
private List<Item> findItemEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
Query q = em.createNamedQuery("Item.findAll");
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}



The ItemJpaController uses the Java Persistence API EntityManager Query object to return a list of items. The ItemJpaController calls Persistence.createEntityManagerFactory which gets an EntityManagerFactory  when it is instatiated. 

The Java Persistence Query APIs are used to create and execute queries that can return a list of results.  The JPA Query interface provides support for pagination via the setFirstResult() and setMaxResults() methods: q.setMaxResults(int maxResult) sets the maximum number of results to retrieve. q.setFirstResult(int startPosition) sets the position of the first result to retrieve.

In the code below, we show the Item entity class which maps to the  ITEM table that stores the item instances. This is a typical Java Persistence entity object. There are two requirements for an entity:

  1. annotating the class with an @Entity annotation.
  2. annotating   the primary key identifier with @Id

Because the fields name, description.... are basic mappings from the object fields to columns of the same name in the database table, they don't have to be annotated.

@Entity
public class Item implements java.io.Serializable {

@Id
private Integer id;
private String name;
private String description;
private String imageurl;
private String imagethumburl;
private BigDecimal price;


public Item() { }

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

...
}

A Wicket PagingNavigator component is used to provide navigation links to the next, previous, first and last page of catalog Items.  The PagingNavigator component maintains a complete page navigator, meant to be easily added to any PageableListView.

<span wicket:id="pager">navigation controls here</span>

Code below for adding creating a PagingNavigator for the dataView and adding it to the ListPage:

public class ListPage extends WebPage {


PagingNavigator pager = new PagingNavigator("pager", dataView);
add(pager);

A Wicket Link component is used to provide a link to click on to navigate to a page with the selected item details.

  <a wicket:id="details" href="#">
<span wicket:id="name" >name</span>
</a>

Code below show the call to  the ItemDetails.link method to create and add the link:

public class ListPage extends WebPage {
// create the DataView component corresponding to the wicketid "rows" attribute in ListPage.html
DataView dataView = new DataView<Item>("rows", itemDataProvider, ROWS_PER_PAGE) {
@Override
protected void populateItem(org.apache.wicket.markup.repeater.Item<Item> repItem) {
' ...
// call ItemDetails to create the link component
repItem.add(ItemDetails.link("details", item));
...

}
};
// add the DataView component to the page
add(dataView);


Code below for creating a BookmarkablePageLink for adding to the dataView, clicking on this link will Navigate to the ItemDetails page, passing the selected Itemid as a parameter.

public class ItemDetails extends BasePage {

public static BookmarkablePageLink<Void> link(final String name, final Item item) {

final BookmarkablePageLink<Void> link = new BookmarkablePageLink<Void>(name, ItemDetails.class);

if (item != null) {
link.setParameter("itemid", item.getItemid());
link.add(new Label("name", new Model<Item>(item)));
}

return link;
}

The ItemDetails page, shown below, displays details about the selected Catalog Item:

<html xmlns:wicket="http://wicket.apache.org/">
<head>
<title></title>
<link wicket:id='stylesheet'/>
</head>
<body>
<span wicket:id='mainNavigation'/>
<table>
<tr>
<td align="right">Name:</td>
<td>
<span wicket:id="name">name </span>
</td>
</tr>
<tr>
<td align="right">Description:</td>
<td> <span wicket:id = "description">
description
</span>
</td>
</tr>
<tr>
<td align="right">Photo:</td>
<td> <img wicket:id="imagethumburl"/> </td>
</tr>
</table>
</body>
</html>
The ItemDetails constructor gets the item data, and adds Labels and a image, for the name, description and photo to the ItemDetails page.
public class ItemDetails extends BasePage {

public ItemDetails(PageParameters params) {
Item item = itemController.findItem(params.getString("itemid"));
add(new Label("name", item.getName()));
add(new Label("description", item.getDescription()));
add(new Image("imagethumburl", new ResourceReference(this.getClass(),item.getImageurl())));
}
 

Hot Deployment with Wicket and Glassfish

  • Incremental compile of all Wicket  artifacts when you save.
  • Auto-deploy of all web artifacts

Conclusion

This concludes the sample application which demonstrates a pet catalog web application which uses  Wicket, JPA, GlassFish and MySQL.

Running the Sample Application

  1. If you haven't already done so, download and install NetBeans IDE , GlassFish , and MySQL Community Server . You can download and install GlassFish with NetBeans as a single bundle.
  2. Follow these instructions to setup Netbeans with the Wicket plugin.
  3. Download the sample code.

Create the Pet Catalog database

In order to run the sample code you first have to create the Pet Catalog database and fill in  the Item table.

  1. Start NetBeans IDE
  2. Ensure that GlassFish is registered in the NetBeans IDE, as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the Servers node. You should see GlassFish v2 in the list of servers. If not, register GlassFish v2 as follows:
      • Right-click the Servers node and select Add Server. This opens an Add Server Instance wizard.
      • Select GlassFish v2 in the server list of the wizard and click the Next button.
      • Enter the location information for the server and click the Next button.
      • Enter the admin name and password and click the Finish button.
  3. Start the MySQL or Java DB database as follows:
    • Click the Services tab in the NetBeans IDE.
    • Expand the databases node. You should see the Java DB database in the list of databases. If you have installed the MySQL server database, you should also see the MySQL database in the list of databases.. Note:  Java DB  comes bundled with Netbeans, you can  download MySQL separately.

    • Right-mouse click on the Java DB or MySQL server database and select Start.
  4. If you installed MySQL, set the properties of the MySQL server database as follows:
    • Right-click on the MySQL server database and select Properties. This opens the MySQL Server Properties dialog box, as shown in Figure 8.

      MySQL Server Basic Properties
      Figure 8. MySQL Server Basic Properties

    • In the Basic Properties tab, enter the server host name and port number. The IDE specifies localhost as the default server host name and 3306 as the default server port number.
    • Enter the administrator user name, if not displayed, and the administrator password -- the default administrator password is blank.
    • Click the Admin Properties tab.
    • Enter an appropriate path in the Path/URL to admin tool field. You can find the path by browsing to the location of a MySQL Administration application such as the MySQL Admin Tool.
    • Enter an appropriate path in the Path to start command. You can find the path by browsing to the location of the MySQL start command. To find the start command, look for mysqld in the bin folder of the MySQL installation directory.
    • Enter an appropriate path in the Path to stop command field. You can find the path by browsing to the location of the MySQL stop command. This is usually the path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin, in the Arguments field, type -u root stop to grant root permissions for stopping the server. The Admin Properties tab should look similar to Figure 9.

      MySQL Server Administration Properties
      Figure 9. MySQL Server Administration Properties

    • Click the OK button.
  5. Right-click on the MySQL server or Java DB database and select Start.
  6. Create the petcatalog database as follows:
    • Right-mouse click on the Java DB or MySQL server database and select Create Database. This will open a create Database window.
    • Enter the database name catalog for Java DB or petcatalog for MySQL.


      For Java DB enter userid password app app as shown below:


       Click O.K. to accept the displayed settings.
  7. Create the tables in the catalog database as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • Right-mouse click on the petcatalog connection and select Connect.
    • Right-mouse click on the petcatalog connection and select Execute Command. This will open up a SQL command window.
    • Copy the contents of the catalog.sql file in the riapetcatalog\exercises\exercise0 directory and paste the contents into the SQL command window, as shown in below:

      Creating Tables in the Database
    • Click the Run SQL icon Run SQL icon (Ctrl+Shift+E) above the SQL command window.
    • Note: It is ok to see this: "Error code -1, SQL state 42Y55: 'DROP TABLE' cannot be performed on 'ITEM' because it does not exist. Line 2, column 1" . This just means you are deleting a table that does not exist.  If you need to delete and recreate the tables you will not  see this message the second time.
  8. View the data in the Pet Catalog database Item table as follows:
    • Underneath Databases you should see a database connection for the petcatalog database. For example MySQL:

      or Java DB:

    • If the database connection is broken like in the following diagram:

      • Right-mouse click on the petcatalog connection and select Connect. as shown below:
      • if prompted for a password, for MySQL leave it blank, for JavaDB enter user app password app.
    • Expand the Tables node below the petcatalog database in the Services window. You should see the item table under the Tables node. You can expand the item table node to see the table columns, indexes, and any foreign keys, as shown in below :
      An Expanded Table Node
      Figure 12. An Expanded Table Node

      You can view the contents of a table or column by right-clicking the table or column and selecting View Data as shown  below:

      Viewing the Contents of a Table
      Figure 13. Viewing the Contents of a Table
  9. Follow these instructions to Create a JDBC Connection pool and JDBC resource.Name the  pool mysql_petcatalog_rootPool and the jndi resource jdbc/petcatalog. Note: you do not have to create a JDBC connection pool and resource if you use the Netbeans wizard to generate JPA entities from database tables as described in this article GlassFish and MySQL, Part 2: Building a CRUD Web Application With Data Persistence.

Running the Sample solution:

If you want to run the sample solution, you have to create the catalog database tables first as described above.

  1. If you haven't already download the sample code and start the NetBeans IDE. Unzip the catalog.zip file which you downloaded, this will create a catalog directory with the project code.
  2. Open the catalog/setup/sun-resources.xml file and verify that the property values it specifies match those of the petcatalog database and jdbc resources you created. Edit the property values as necessary.
  3. Open the catalog project as follows:
    • In NetBeans IDE, click Open Project in the File menu. This opens the Open Project dialog.
    • Navigate in the Open Project dialog to the catalog  directory and click the Open Project button.

    In response, the IDE opens the catalog project.  You can view the logical structure of the project in the Projects window (Ctrl-1).
  4. Run the catalog by right-clicking on the catalog project in the Projects window and selecting Run Project. The NetBeans IDE compiles the application, deploys it on Glassfish, and brings up the default page in your browser.  (at http://localhost:8080/catalog/).

For more information see the following resources:

  • JPA/Hibernate and Wicket Repeating Views with Netbeans
  • Using Wicket with Netbeans
  • Wicket in Action
  • Apache Wicket Home
  • Track your running miles using Apache Wicket, GlassFish, NetBeans, MySQL, and YUI Charts
Database connection MySQL Java (programming language) GlassFish

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How Agile Architecture Spikes Are Used in Shift-Left BDD
  • Securing Cloud-Native Applications: Tips and Tricks for Secure Modernization
  • Beyond Coding: The 5 Must-Have Skills to Have If You Want to Become a Senior Programmer
  • Key Elements of Site Reliability Engineering (SRE)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: