Detachable Models with Wicket (Attempt one)

Here is the Code. To run it, unzip it. You need Java and Maven. To run it and view it, just issue mvn jetty:run . Point your browser to http://localhost:8080 . You can also import it into Eclipse using File->Import->Existing Projects into Workspace and then select the directory where you unzipped it. This is built upon code created for the Wicket In Action book, although the example in the book (Chapter 4.3) for this area is just fragments that compile, yet don’t run.

The great thing about Wicket is that it stores the state on the server and can work with the back button. The bad thing about this is that the Wicket models you provide for your pages get serialized and stored in a cache. Create a successful website and you may be doomed to a lot of cache of repeated that was content fetched from the database. Wicket uses what is calls detachable models to counter this problem. This sample has the detachable model working, yet I am not sure it is doing its job. The good part is that it works and now it is just a process of seeing where the problem lies. Caching is supposed to work so that when state is saved, the objects contained in the LoadableDetachableModel are not serialized. At load time, it uses the load method. Download the code and look at the following areas.

First, I created the html for a list view.


<div wicket:id="cheeses">
<h3 wicket:id="name">Gouda</h3>
<p wicket:id="description">Gouda is a Dutch...</p>
<span wicket:id="price">$1.99</span>
<a wicket:id="add" href="#">add to cart</a>

Then I created the that corresponds to the html.

public class Index extends CheesrPage {
public Index() {

// LoadableDetachableModel<List<Cheese>>
CheeseDetach myDetach = new CheeseDetach(getDAO());
// ListView<Cheese> bound to "cheese" on html
CheeseList myCheeseList = new CheeseList("cheeses", myDetach, getCart());
// Add it to the page

The java code above creates a LoadableDetachableModel called myDetach. It uses a CheeseDAO by calling getDAO() to construct it. Then, it creates a ListView called myCheeseList passing the myDetach (LoadableDetachableModel) to it. It finally adds it to the page.

The interface for CheeseDAO extends Serializable. I had to do this so it would not
produce errors.

public interface CheeseDAO extends {
public Cheese getCheese(Long id);
public List<Cheese> getCheeses();

This is troubling. It should not produce errors if it is not trying to serialize it. Ugh! Remove the extends from the interface, recompile and watch the output as it runs. It will throw an error (or is it an exception that recovers?) complaining that it is not serializable. Ugh again!

The bonus side is that I did get an LoadableDetachableModel working for a ListView. That was a little tricky! I may be complaining about nothing. Look at the following files from the code.


These files contain the essential details. I hope to gain more insight as to whether this really is not caching.

Posted in Wicket | Comments Off on Detachable Models with Wicket (Attempt one)

Bind to your model better with Wicket!

In this post, I still follow the Wicket in Action book, yet continue with the process of breaking out the concept into one simple project. This post takes the model (Customer object) and ties it to the page using the CompoundPropertyModel<Customer> object. I use paramaterized generics (<Customer>) part for the methods, so no casting of the return value needed for our callback (onSubmit). The code for this can be downloaded as from my site and imported in eclipse. To run the code, you need Maven and Java. To run it, just use mvn jetty:run and point your web browser to http://localhost:8080/

The process is as follows. We create object used for model. Set the default model using the setDefaultModel for the page which extends WebPage.

We set labels so that they will use the getters from the default model. Maybe someday Java will have properties like Pascal! First, here is the Java code in creating the Customer object (our Model of MVC). I use setDefaultModel to set the model for our page (Index.html). I don’t know exactly why it is not setModel() like it is in our form, but I am still getting the details on Wicket, so I hope to figure out why later.

customer = new Customer();
customer.getAddress().setStreet("123 Easy Street");

myModel = new CompoundPropertyModel<Customer>(customer);

firstNameLabel = new Label("firstName");
lastNameLabel = new Label("lastName");
addressLabel = new Label("address.street");

This following the html for the Labels. The labels match the attributes for the object.

<td><code>firstName in Label</code></td>
<td wicket:id="firstName"></td>
<td><code>lastName in Label</code></td>
<td wicket:id="lastName"></td>
<td><code>street.address in Label</code></td>
<td wicket:id="address.street">1234 Any Street</td>

Now, we shall add the form(myForm), passing the model as an argument to the form. At first, I thought that myForm would get the model from the Index page, but it does not, so I passed it the model as an argument for the constructor. In myForm, we first add the model, and then the fields. The attributes for the fields match the names of the attributes in the Customer object model, and therefore, the model binds them directly matches the fields directly to the object. Below, first is the java code and then the html.

The Java code (


fnameField = new TextField<String>("firstName");

lnameField = new TextField<String>("lastName");

streetField = new TextField<String>("address.street");

Java code in

myForm = new Form1("myform",myModel);

The html (Index.html)

<tr><td>First Name</td><td><input type="text" wicket:id="firstName" /></td></tr>
<tr><td>Last Name</td><td><input type="text" wicket:id="lastName" /></td></tr>
<tr><td>Street</td><td><input type="text" wicket:id="address.street" /></td></tr>

And, when the user hits the submit button for the form, we create a callback for onSubmit behavior.

protected void onSubmit() {
Customer customer =  getModelObject();
String street = customer.getAddress().getStreet();
// Probably should use logging here!
System.out.println("Customer street is " + street);
// do something with/to the customer

As the book notes, this ties the data close to the form construction. Make an UML class diagram of your model, hand it to your html designer, and it seems that you are almost all good to go. I am sure there are still little devils running through the details, but this provides good abstraction and takes the developer away from dealing with low level http dirty work. Yet, the book notes that the referenced attributes in quotes can’t be easily refactored if need be. I find that it makes MVC really clean and look forward to more.

Posted in Wicket | Comments Off on Bind to your model better with Wicket!

OpenOffice BASE and HSQLDB in server mode

The sample database for this post can be downloaded and used with GNU/Linux. It can also be adapted to Windows and Mac.

OpenOffice Base uses hsqldb as its back end database in embedded mode. If you are a developer like me, this doesn’t normally allow you to connect other tools to the database you have created in Base. In this post, I shall explore using hsqldb in server mode. This way, you get the luxury of using Base’s interface, yet at the same time the capability to connect other tools to it such as the JBOSS tools tutorial for developing a web application to display and edit your data. If you are a PERL hacker, you can use hsqldb-ber to connect to the server. In addition, the database server is started using Maven, so your database is even extra small when you zip it, because Maven is automatically downloading the jar for when you start the database.

These are the steps to follow. First, make sure that you have Maven installed on your system and java. If you don’t, install it/them using the following command:

$ sudo apt-get install maven2
$ sudo apt-get install openjdk-6-jdk
$ sudo apt-get install openjdk-6-jre

Start the hsqldb employee database using the following command:

$ ./

I assume that you have Base already installed. Assuming that you do, you can open the database in Base by just double clicking the employee.odb and it will open in OpenOffice Base. When you open the database file, you can browse the tables, a sample query I created named itemsorderedby363 and a report named by the same thing. The odb file contains a setting to the database in server mode. You can see the database settings by going to Edit->Databse->Properties. You can connect other applications to the database, do development, and at the same time have the luxury of using OpenOffice Base GUI interface. The data in the database comes from JBoss Demo Employee Database, yet adds the connection to the database and uses Maven for the hsqldb jar dependency.

I really like hsqldb and its robustness for development. You can easily zip your database and transport it around from machine to machine with zero configuration.


Posted in Uncategorized | Comments Off on OpenOffice BASE and HSQLDB in server mode

Callbacks and Wicket

I don’t believe starting with Anonymous Inner Classes (AIC) is a good way to get started when doing event driven programming. For this post, I took the Cheesr application from the Wicket in Action book and removed the AICs and put them in their own classes. The end result is an and an Index.html with a visible one for one correlation between Wicket tags and the Java code. The second thing I like is that you can see in the structure of the callback classes for the event driven model. Here is the code. First, I show the, its corresponding Index.html and the three callback classes:,, and Note that in the callback classes that by providing the @Override annotation that the compiler will warn if somehow you misspell your method that overrides the default behavior that usually does nothing. You can download the whole code for this sample and import it into Eclipse using File->Import…->Existing Project into Workspace. Navigate to the directory where you unzipped

Below is the html for Index.html.

<div  wicket:id="cheeses">
<h3 wicket:id="name">Gouda</h3>
<p wicket:id="description">Gouda is a Dutch...</p>
<span wicket:id="price">$1.99</span>
<a wicket:id="add" href="#">add to cart</a>
<div wicket:id="navigator"></div>

<div id="cart">
<div wicket:id="shoppingcart"></div>
<input type="button" wicket:id="checkout" value="Check out" />

This is the corresponding Java code for Note how “cheses”, “navigator”, “shoppingcart”, and “checkout” line up nicely between the above html wicket tags and the references in the

PageableListView cheeses =
new CheesePageList("cheeses", getCheeses(), 4, this, getCart());

add(new PagingNavigator("navigator", cheeses));
add(new ShoppingCartPanel("shoppingcart", getCart()));
add(new CheckoutLink("checkout",getCart()));

Now time for the callback classes. Some of the generic parameters still might be off, but I think this emphasizes what you can do and how the structure works. I put the callbacks in their own package.

First is AddCheeseCB. I think rather than using the <T> parameter, I should have used what the link actually uses, which I believe is <String>, but I am a little unclear on that at them moment. If you know, let me know.

public class AddCheeseCB<T> extends Link<T> {
private Cart myCart;
private static final long serialVersionUID = 1L;

public AddCheeseCB(String id, IModel<T> model, Cart cart) {
super(id, model);
myCart = cart;

public void onClick() {
Cheese selected = (Cheese) getModelObject();

Below is the code for the CheckoutLink. Note the behavior that we are implementing is onClick and isVisible. When we construct the object for the behavior, we have to give it a reference to the cart, hence the constructor with the additional arguments. I made the default constructor private. I am not sure if this is the correct approach, but it works for now.

public class CheckoutLink extends Link<String> {
Cart myCart;
private static final long serialVersionUID = 1L;

private CheckoutLink(String id) {

public CheckoutLink(String id, Cart cart) {
myCart = cart;

public void onClick() {
setResponsePage(new CheckOut());


public boolean isVisible() {
return !myCart.getCheeses().isEmpty();

Now the code for the PageableListView. I believe I specified the generic parameter <Cheese> correctly on this one.

public class CheesePageList extends PageableListView<Cheese> {
private Cart myCart;
private Index myIndex;
private static final long serialVersionUID = 1L;

public CheesePageList(String id,
IModel<? extends List<? extends Cheese>> model, int rowsPerPage) {
super(id, model, rowsPerPage);

public CheesePageList(String id,
List<Cheese> list, int rowsPerPage,
Index index, Cart cart) {
super(id, list, rowsPerPage);
myIndex = index;
myCart = cart;

protected void populateItem(ListItem<Cheese> item) {
Cheese cheese =  item.getModelObject();
item.add(new Label("name", cheese.getName()));
item.add(new Label("description", cheese.getDescription()));
item.add(new Label("price", "$" + cheese.getPrice()));

Cart myCart = myIndex.getCart();

// Create a real callback rather than an anonymous inner class!
AddCheeseCB myAddCheese = new AddCheeseCB("add", item.getModel(), myCart);



Download it and try it out. In order to launch it, all you have to do is have Maven installed and execute mvn jetty:run. Wicket is looking like it provides a good clean approach to developing Web Applications, but there is still more to explore, especially with the model that I wrote about in the last post.

Posted in Wicket | 3 Comments

Using Generics and a Form with Wicket

This blog post I will take a look at using a form with Wicket and binding it to an object using a PropertyModel along with Generics. I just started digging into generics in Java and even after reading a tutorial on generics, the use of <T> and the wildcard value <?> still is not completely clear to me. Yet, I think with use of Wicket, it will help my understanding and hopefully yours too. Enough fluff, I shall get to the details. The Generics add type safety and eliminate the need for casting as was originally done in the book example.

The example code for this blog can be downloaded. This sample code is once again built upon the examples used in the book titled Wicket in Action by Dashorst et al. The project is Maven, so if you have the Maven Plugin for your Eclipse, download the file, unzip it, and import the File->Import->Existing Projects into Workspace. The project name is hippo02. For this project, it has a Form and, the Customer class which along with its attributes is also composed of the Address class. The form has the coresonding html:

<form wicket:id="myform">
<tr><td>Name</td><td><input type="text" wicket:id="name" /></td></tr>
<tr><td>Street</td><td><input type="text" wicket:id="street" /></td></tr>
<tr><td colspan="2"><input type="submit" value="Submit" /></td></tr>

The form contains the wicket identifier myform for the form along with two other identifiers for the text fields: wicket:id=”name” and wicket:id=”street”

The two following snippets detail the classes involved: Customer and Address. A Customer has an Address. First, the Customer class. Note that the class must be made serializable so that Wicket can save state. I omitted the getters and setters. Check the hippo source if you want to see them. Next, I created the Form1 specifying the generic parameter <Customer>. So, when the object model is fetched as can be seen in the onSubmit method, the type does not need to be cast. Now, I was a little uncertain about the TextField portions, but it seems that they should be set as <String> parameters. The part that I find somewhat confusing is the specifying the class attribute and the attribute for the text field. In the Form1 class, you will note that it specifies “firstName” in the property model, and then when the TextField is created using the just created property model, it uses the value “name” that matches the wicket:id attribute given in the html.

Now that this is all created, a Form1 object is created in the class and bound to the wicket:id attribute name “myform”.

This is what happens when the program is run. When a Form1 is created in, a Customer object is created. When the user enters values and presses submit, the onSubmit callback action sets the values entered into the two fields.

The plumbing seems a little tricky here, but I thought by breaking out these Anonymous Inner Classes (AIC) it would help break the details for the form. Plus, if you see a correction on the use of Generics, let me know. I hope this helps illustrate the use of PropertyModel and a Wicket Form<T>.

Customer class:

public class Customer implements Serializable {
  private String firstName;
  private String lastName;
  private Address address = new Address();


Address class:

public class Address implements Serializable {
  private String name;
  private String street;
  private String city;
  private Integer zipcode;

  // [snip]

Form class:

public class Form1 extends Form<Customer> {

 private static final long serialVersionUID = 1L;
 private TextField<String> nameField;
 private TextField<String> streetField;
 private PropertyModel<String> namePropModel;
 private PropertyModel<String> streetPropModel;
 private Model<Customer> myModel;
 public Form1(String id) {
 Customer customer = new Customer();
 myModel = new Model<Customer>(customer);
 namePropModel = new PropertyModel<String>(customer, "firstName");
 nameField = new TextField<String>("name",namePropModel);
 streetPropModel = new PropertyModel<String>(customer, "address.street");
 streetField = new TextField<String>("street", streetPropModel);

 protected void onSubmit() {
 Customer customer =  getModelObject();
 String street = customer.getAddress().getStreet();
 // do something with/to the customer


Inclusion into

Form1 myForm = new Form1("myform");
Posted in Wicket | Comments Off on Using Generics and a Form with Wicket

Wicket meets Hibernate

I got Hibernate and Wicket working together. It is simple and perhaps still needs some tweaking, but I was happy to have joined the two together. These instructions are intended for Ubuntu, but can be adapted for Windows too. I am especially intrigued that the OpenOffice Database runs on both. You need to have mvn installed too. If not, do the sudo apt-get install maven2 .

I worked for a while with Hibernate, especially with the code from the book titled Harnessing Hibernate. Many of the examples were great and it goes through many details, yet at the end, the Stripes examples don’t seem to work. I ended up at Barnes and Nobel buying a copy of Wicket in Action. I hacked through the Cheesr application, nice concept, yet they seem to leave out how to get the initial infrastructure. What I have really wanted to do is marry the two together.  I actually believe this is a job for Spring, but these things have to occur in steps, so took material from Hibernate Tutorial Refined blog and I was thinking that it shouldn’t be too hard to add the Hibernate to the simple Cheesr application created by the authors of Wicket in Action, Dashorst et al. I grabbed the HibernateUtil class that loads the configuration and session factory. Now, I just needed to load the Cheeses using the Hibernate Query Language. It was simple “from Cheese”, meaning give me everything from the Cheese class. At first, I put the table name “CHEESE”, a mistake! We are dealing with objects, not tables, doh! And, to top it off, I added the database to OpenOffice base. You can start open Office base and open the cheese.odb file and modify the cheeses. You have to restart the Cheesr application for it to take effect, but I find it really cool. The code is very concise too. Yet, I am sure I am missing some exception handling, but I am happy to get this working. So, here are the steps.

  1. Get the code
    $ wget
  2. Unzip it
  3. These are the following Maven commands to start the database, import for Eclipse, compile, clean, and run the application
    $ mvn exec:java -Dexec.mainClass="org.hsqldb.Server" \
      -Dexec.args="-database.0 file:db/data/tutorial -dbname.0 cheeses"
    $ mvn -DdownloadJavadocs=true -DdownloadSources=true eclipse:eclipse
    $ mvn compile
    $ mvn clean
    $ mvn jetty:run

Once you have it running, add the hsqldb.jar file to OpenOffice. In OpenOffice, choose the following menu item.


You will see the>Java item. Select it. To the right, there will be a button labeled Class Path… . Click it. Click the button labeled Add Archive… Locate the hsqldb.jar file in your repository. Maven stores the files it downloads in your $HOME/.m2/repository directory. Navigate to the directory similar to the following and select the hsqldb jar file.


Once you have completed this, open the cheese database in OpenOffice. It is named cheeses.odb and you can double click it to open it. Once opened, you can change the price of cheeses in the CHEESE table, restart the Cheesr application and see the changes!

The great thing is how easy Hibernate makes the code look. The tricky part is getting the configuration files. I added the src/main/resources/hibernate.cfg.xml and the src/main/resources/com/brie/dtoo/Cheese.hbm.xml for configuration. In addition, I added the class to do the configuration. In CheesrApplication, I added the private variable along with the initialization code. org.hibernate.Session myHibSession =  HibernateUtil.getSessionFactory().getCurrentSession(); Then, in the constructor, I execute the query that assigns the result to the cheeses list.

In order to access the page, use the following URL. http://localhost:8080/zebra03



Posted in Hibernate, Wicket | 2 Comments

Wicket Adventures

While the World Wide Web has been around for a long time, it seems like building web applications is still difficult. The problem, one has to write glue code to handle a lot of plumbing. I decided to try Wicket and I believe there a number of good features about it. It leaves logic out of the web page so that web page designers can do their job and programmers can do theirs. I bought the book titled Wicket in Action by Martijn Dashortst and Eelco Hillenius. It has a series of examples, but they are bundled into one giant application. At the same time, Maven provides an archetype that will build the basic layout and structure for a Wicket project. When I started with a base Wicket application from Maven, I was at a loss as how to get the example code from the book working. Here are my results. If the authors do a second edition, I hope they bridge this gap.

In order to use the example code, you need two things: one, maven and two, a java compiler. To use maven, either apt-get install it or download it. To see if both are working do the following.

$ javac -version
javac 1.6.0_25
$ mvn
<You should see some output here>

Now, just download each of the zip files. To run it, do the following:

$ mvn jetty:run

Point your web browser to http://localhost:8080 and you are good to go.

You can also import the project into Eclipse. First, make sure that you have the Maven plugin. Then, go to File->Import… Existing Project and select the project directory. If you want to make a war file for any of the sample projects, do the following:

$ mvn package

The resulting war file will be in the target directory.

I put together projects that deal with and only with the concepts presented. These examples are from Chapter 3 that uses the Cheesr application.


This code just does the basic layout using the Index.html as the main page, the Cheesr*.java classes to support the application. If you run it, you will get just the logo. But, it is a good starting point.


This adds the items to the page and the simple cart concept.


This adds the CheckOut panel and the checkout page. I also added a separate callback class for the add link. All the examples I have seen in the book contain anonymous inline classes (AIC). The downside is if you use the same logic in two different areas, you have to cut and paste. With a separate class, you can do code reuse. Plus, AICs look weird. Anyway, this is the demo of a separate callback the panel in addition to the checkout code. I like the Cheesr code. You can really see the power of Wicket.


Posted in Wicket | Comments Off on Wicket Adventures

Making a Servlet with Hibernate

These are the details I followed for making a servlet with Hibernate. This will take off from the last post with Many to Many. It is a rehash from the original Hibernate documentation.  Make sure that you have .m2/settings.xml so that it has the jboss repository. See my Hibernate Tutorial Refined for details. For this tutorial. You will also need Tomcat. Download it. Unzip it somewhere else on your system.

Start this tutorial by downloading the base code and unzip it. The ‘$’ indicates the command prompt. Don’t type it. I assume you are using GNU/Linux for this tutorial. It will work on Windows too with minor modification.

$ wget
$ unzip
$ cd hib-serve

Make sure that you are in the directory that contains the pom.xml file. Start the HSQLDB database as a server (all on one line):

$ mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial"

Open a separate command prompt window and start the Database Manager (all on one line). Make sure that you are in the directory with the pom.xml file.

$ mvn exec:java -Dexec.mainClass="org.hsqldb.util.DatabaseManagerSwing" -Dexec.args="-url jdbc:hsqldb:hsql://localhost/ -driver org.hsqldb.jdbcDriver"

Make the directory for the Servlet configuration. Download the configuration file and move it to the correct place. Basically, this configures the url that maps to the servlet class.

$ mkdir -p ./src/main/webapp/WEB-INF
$ wget
$ mv web.xml ./src/main/webapp/WEB-INF

The following is the code for the Servlet. Download it, copy it to the correct place.

$ wget
$ mv src/main/java/org/hibernat/tutorial/web/

The EventManager had all private methods. Replace it with one that has public methods that can be used by the Servlet.

$ wget
$ mv src/main/java/org/hibernate/tutorial/

Compile the project using the following Maven command:

$ mvn compile

This example uses the property, so it will automatically create the schema when the program is run. Now add a person to the event using the Event manager from the command line with the following command (all on one line):

$ mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="addpersontoevent"

Check the database manager. You should see an event. Now, create a war file using the following command. It will create a hib-create.war file in the target subdirectory.

$ mvn package

Now copy the hib-create.war to your Tomcat webapps directory. Replace <Tomcat-home> with where you unziped Tomcat.

$ cd target
$ cp hib-create.war <Tomcat-home>/webapps

Start Tomcat.
$ cd
$ bin/

Tomcat should start. Go to your browser, and you should be able to access the servlet and enter an event.


Add an event and you are good to go. This concludes the simple creation of a servlet with Hibernate and Maven.

Posted in Hibernate | Comments Off on Making a Servlet with Hibernate

Generating domain classes from hbm files in Hibernate

Hibernate offers the capability to generate both the database schema and the java class files for the domain model when you specify the model using the .hbm.xml files.  You can accomplish this using the hibernate3-maven-plugin. I was not able to find too much clear documentation on how to accomplish this, but I was able to hack together a configuration that works. Once again, you start with Maven installed and make sure that you have the .m2/settings.xml file for Maven pointing to the JBoss nexus repository. See my hibernate tutorial refined for instructions on doing this. Assuming you have Maven installed and the settings for the JBOSS tutorial installed, these are the steps. The lines that you type in commands, don’t type the ‘$’. First, download the sample code using the following command:

$ wget

Unpack it using tar. This works on GNU/Linux.

$ tar zxvf hibcodegen.tgz

cd into the directory where you unpacked the code.

$ cd hibcodegen

Do an ls of the directory and you should see the pom.xml file. Start two more terminals having the same current working directory as the pom.xml file. In window 1, start the database server, window 2, the database manager, and 3, we will use to complete the rest of the commands. The following is the command to start the database, HSQLDB (all on one line):

$ mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial -dbname.0 meetings"

Start the dababase manager with the following command (again all on one line!):

$ mvn exec:java -Dexec.mainClass="org.hsqldb.util.DatabaseManagerSwing" -Dexec.args="-url jdbc:hsqldb:hsql://localhost/meetings -driver org.hsqldb.jdbcDriver

You database manager should show the database without any tables. Press Ctrl-R to verify this on the database manager. Now, comes time for the auto code and schema generation. This is true magic!

This will generate the class in the src/main/java/com/brie/domain directory:

$ mvn hibernate3:hbm2java

Examine the pom.xml file for the plugins area. The hbm2java takes the Meeting.hbm.xml and automatically generates the Java class file with getters, setters, etc. Of course, if you modify the class file, and run the command again, it will clobber the file with the newly generated one, but aside from those deficiencies (there are ways around this), this very slick.

To add to the “coolness” factor, the following command generates the shema:
$ mvn hibernate3:hbm2ddl

Go to the database browser, type Ctrl-R, and the new Meeting table will show.

Run a sample program that creates a new object and save it.
$ mvn exec:java -Dexec.mainClass="com.brie.NativeApiIllustration"

Use the database manager to view the object just created.

select * from meeting

Using the .hbm.xml file to generate the java classes and the schema makes for some interesting tool ideas. I hope to envision the day when one can use Violet to generate a class diagram and it generates the hbml.xml files. I hope this provides a concrete example for using hbm2java and hbm2ddl. I am sure there could be improvements to my approach, so I will be looking to find them in the future.


Posted in Hibernate | Comments Off on Generating domain classes from hbm files in Hibernate

Adding many-to-many in Hibernate

In this post, I will demonstrate how to do a many-to-many relation in Hibernate. A Person(s) can attend many Event(s) and an Event(s) can have many Person(s). This follows the initial creation of the simple mapped class describe in my Hibernate getting started post. Once again, this post is built off the documentation included in the 3.6.2-Final release and the frustration getting the tutorial to work. First, download the working version (commands follow for GNU/Linux) of a simple mapped class, untar it, and change into the directory containing the sample code. You will need Maven installed too. If not, check my Start post for instructions for Maven. Then, we will follow the steps to add many-to-many relationship. The following are the commands to enter. Don’t type the ‘$’ character.

$ wget
$ tar zxf myfirst-hibernate.tgz
$ cd myfirst-hibernate

Now, open two separate windows with the same current working directory and start the database and the HSQL Database Manager. If for some reason, you already have the database running from the first example, you can leave it running. Type the following all on one line:

$ mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial"

$ mvn exec:java -Dexec.mainClass="org.hsqldb.util.DatabaseManagerSwing" -Dexec.args="-url jdbc:hsqldb:hsql://localhost/ -driver org.hsqldb.jdbcDriver"

Add the Person class

$ wget
$ mv src/main/java/org/hibernate/tutorial/domain

Now that you have added the Person class, add the mapping for Hibernate.

$ wget
$ mv Person.hbm.xml src/main/resources/org/hibernate/tutorial/domain/

If you examine the contents of the .hbm.xml file, the following creates the many-to-many mapping. The table used to hold the many-to-many mapping will be named PERSON_EVENT. The id for the Person will be mapped to the PERSON_ID column, and the id of the Event will be mapped to the EVENT_ID column.

<set name="events" table="PERSON_EVENT">
<key column="PERSON_ID"/>
<many-to-many column="EVENT_ID"/>

You will also notice that each Person has a set of email addresses. This is mapped with the following configuration on the hbm file.

<set name="emailAddresses" table="PERSON_EMAIL_ADDR">
<key column="PERSON_ID"/>
<element type="string" column="EMAIL_ADDR"/>

Now, fetch the configuration for hibernate.

$ wget
$ mv hibernate.cfg.xml src/main/resources

If you examine the hibernate.cfg.xml file, you will notice that it has the following line that tells Hibernate about the Person class.

<mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>

Now modify the class, so that we can create a person and an event, and associate them with each other

$ wget
$ mv src/main/java/org/hibernate/tutorial

If you examine the code for EventManager, you will notice that it now will check for the argument named “addpersontoevent”. Compile the code using the following command. If all goes well, you should see “success”.

$ mvn compile

Run the newly compiled program using the following Maven command (all on one line). It will run the Main class with the “addpersontoevent” argument.

$ mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="addpersontoevent"

If all went well, the program will have run an inserted the data into the Person table, the Event Table, and the corresponding associations into the Person_Event table to map the relationship between the Person and the Event. The email address set is mapped into the Person_Email_Addr table. Use the following queries to view the results in the database. Enter the following queries one at a time into the HSQL database manager. Before doing so, you may have to refresh the database using the Ctrl-R command.

select * from events
select * from person
select * from person_event
select * from person_email_addr

You will note that in the above example that the tables were created automatically. This is because the hibernate.cfg.xml file has been configured to automatically create the database schema using the following directive.

<property name="">update</property>

This concludes the demonstration for mapping a many-to-many classes for Hibernate. If something happened with your modifications, check the following download that has the completed additions.


Posted in Hibernate | 2 Comments