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
or
$ sudo apt-get install openjdk-6-jre

Start the hsqldb employee database using the following command:

$ ./startdb.sh

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 Index.java 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 Index.java, its corresponding Index.html and the three callback classes: AddCheeseCB.java, CheckoutLink.java, and CheesePageList.java. 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 zebra04.zip.

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>
<p>
<span wicket:id="price">$1.99</span>
<a wicket:id="add" href="#">add to cart</a>
</p>
</div>
<div wicket:id="navigator"></div>

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

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

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

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

@Override
public void onClick() {
Cheese selected = (Cheese) getModelObject();
myCart.getCheeses().add(selected);
}
}

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) {
super(id);
}

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

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

}

@Override
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;
}

@Override
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);
item.add(myAddCheese);

}

}

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">
<table>
<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>
</table>
</form>

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 Index.java 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 Index.java, 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();

  //[snip]
}

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) {
 super(id);
 
 Customer customer = new Customer();
 myModel = new Model<Customer>(customer);
 setModel(myModel);
 
 namePropModel = new PropertyModel<String>(customer, "firstName");
 nameField = new TextField<String>("name",namePropModel);
 add(nameField);
 
 streetPropModel = new PropertyModel<String>(customer, "address.street");
 streetField = new TextField<String>("street", streetPropModel);
 add(streetField);

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

}

Inclusion into Index.java:

Form1 myForm = new Form1("myform");
add(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 http://brie.com/brian/wicket/zebra03.zip
  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.

Tools->Options

You will see the OpenOffice.org->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.

/home/brian/.m2/repository/hsqldb/hsqldb/1.8.0.10/hsqldb-1.8.0.10.jar

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 HibernateUtil.java 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 CheesrApplication.java 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

Enjoy!

brian

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.

Girrafe

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.
http://brie.com/brian/wicket/giraffe.zip

Zebra

This adds the items to the page and the simple cart concept.
http://brie.com/brian/wicket/zebra.zip

Zebra02

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.
http://brie.com/brian/wicket/zebra02.zip

 

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 http://brie.com/brian/hibernate/servlet/hib-serve.zip
$ unzip hib-serve.zip
$ 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 http://brie.com/brian/hibernate/servlet/web.xml
$ 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 http://brie.com/brian/hibernate/servle/EventManagerServlet.java
$ mv EventManagerServlet.java 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 http://brie.com/brian/hibernate/servlet/EventManager.java
$ mv EventManager.java src/main/java/org/hibernate/tutorial/

Compile the project using the following Maven command:

$ mvn compile

This example uses the hbm2ddl.auto 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/startup.sh

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

http://localhost:8080/hib-serve/eventmanager

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 http://brie.com/brian/hibernate/hibcodegen.tgz

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 Meeting.java 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 Meeting.java 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.

brian

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 http://brie.com/brian/hibernate/step02/myfirst-hibernate.tgz
$ 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 http://brie.com/brian/hibernate/step02/Person.java
$ mv Person.java src/main/java/org/hibernate/tutorial/domain

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


$ wget http://brie.com/brian/hibernate/step02/Person.hbm.xml
$ 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"/>
</set>

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 http://brie.com/brian/hibernate/step02/hibernate.cfg.xml
$ 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 EventManager.java class, so that we can create a person and an event, and associate them with each other


$ wget http://brie.com/brian/hibernate/step02/EventManager.java
$ mv EventManager.java 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="hbm2ddl.auto">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.

http://brie.com/brian/hibernate/step02/step02-hibernate.tgz

brian

Posted in Hibernate | 2 Comments

Hibernate Tutorial refined

This tutorial refines what is presented in the Tutorial section that is included with the Hibernate documentation for the 3.6.2-Final release. I had a few problems while working through the tutorial contained in the documentation, thus this is my attempt to simplify things so that others can also understand how Hibernate works. The code listings contain commands that you enter at the command line. The ‘$’ character indicates that this is the prompt. Don’t type it. The code is also available as a full download if you don’t feel like entering it in increments.

First, we need to do a simple configuration setup to get Maven working. I assume that you have Maven installed. If you don’t grab a copy and install it. Copy the settings.xml (bellow) file into your Maven directory. You need to configure Maven so that it can see the JBoss repository for this tutorial to work. The file that needs modification is located in the $HOME/.m2/settings.xml . Download the copy I have and place it there. If you are already a Maven user and have custom settings, make the modifications I included in this settings.xml file.

$ wget http://www.brie.com/brian/hibernate/start/settings.xml
$ cp settings.xml $HOME/.m2

Make a directory for your first Hibernate Project

$ mkdir myfirst-hibernate

This is the way you enter code. In this directory, you are going to place a pom.xml, which you can download from my site.  The pom.xml is the Maven file that tells what files are in the project, the structure, etc.

$ cd myfirst-hibernate
$ wget http://www.brie.com/brian/hibernate/start/pom.xml

Now, start the database server using the following command (all on one line):

$ mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial"
Start the DB Manager in a separate window from the same directory. Enter the following (all on one line):
$ mvn exec:java -Dexec.mainClass="org.hsqldb.util.DatabaseManagerSwing" -Dexec.args="-url jdbc:hsqldb:hsql://localhost/ -driver org.hsqldb.jdbcDriver"

Now you have a pom.xml file that details the dependencies for your project, a running database server (HSQLDB) and the database manager. Other than that, you have no code. We will fix that. Open yet a third terminal window. Your current working directory should be that of the pom.xml. Do an ls command just to be sure. Now create the following directories. If you are not used to using Maven, the source files go into src/main/java and the accompanying .hbm.xml files go into a resource directory.

$ mkdir -p src/main/java/org/hibernate/tutorial/domain
$ mkdir -p src/main/java/org/hibernate/tutorial/util
$ mkdir -p src/main/resources/org/hibernate/tutorial/domain

We will now create our first Java class: Event.java. To simplify this blog, just download the class file and either copy it to the directory or type it in. I assume that you are in the directory that has the pom.xml file.

$ wget http://www.brie.com/brian/hibernate/start/Event.java
$ mv Event.java src/main/java/org/hibernate/tutorial/domain

Now, we will add a corresponding mapping file from Hibernate that will map an Event object to the database. The mapping file maps each attribute to a column, yet when it comes to creating an identifier for the object, we let Hibernate handle it. The mapping file goes into a parallel directory to the that of the class.


$ wget http://www.brie.com/brian/hibernate/start/Event.hbm.xml
$ mv Event.hbm.xml src/main/resources/org/hibernate/tutorial/domain

The project now has a class (Event.java), and a mapping file, but now it misses the file that tells hibernate what database to connect to and what type of database it is. It is the main configuration file, hibernate.cfg.xml . It also tells Hibernate to create the database schema automatically, something good for a tutorial, but not quite as wise for production. As before, download it and move it to the proper place.

$ wget http://www.brie.com/brian/hibernate/start/hibernate.cfg.xml
$ mv hibernate.cfg.xml src/main/resources

Compile your code using Maven. It should compile without errors, assuming the repository, etc has not changed since this was written. You should execute this command at the same location as the pom.xml file is located.


$ mvn compile

If all is well, you now have a way to connect. The original tutorial off which this is based uses a utility class. I believe a different approach now works, but we will follow what works. Download the utility class and move it to the proper area. It uses a singleton pattern.


$ wget http://www.brie.com/brian/hibernate/start/HibernateUtil.java
$ mv HibernateUtil.java src/main/java/org/hibernate/tutorial/util

Now is the time to do something with this domain that we have created. We will write a small program that creates an Event object. The event will get saved to the database automatically. First, get the code, for the EventManager, compile, and then run it. Refresh the dbmanager tool so that you can see the tables and query for your newly created Event.


$ wget http://www.brie.com/brian/hibernate/start/EventManager1.java
$ mv EventManager1.java src/main/java/org/hibernate/tutorial/EventManager.java
$ mvn compile
$ mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store"
$ mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="list"

If all worked well, check the graphical DataBase manager and query for the new Event. Enter the text, and press execute. You may have to press the refresh button to see the newly created table in the HSQLDB database.


select * from events

This concludes this brief introduction to using Hibernate. I will add the second class in another blog where I will add the Person class presented in the original tutorial and the web application, for now. You can grab the full code from here. Just remember to also add the settings.xml to your Maven configuration.

-brian

Posted in Hibernate | 1 Comment

Getting Started

I have been hacking Hibernate to figure out how to make this Object Relational Mapping to work. The idea of Hibernate is great, but the details of using it seem to be dispersed and confusing. The original technique uses the hbm.xml file that maps a class to fields in the database. Perform your crud operations on your object and it automatically gets persisted to your database. The new technique uses annotations. Drop annotations in your code and it will tell Hibernate how to persist the object, no separate hbm.xml file required. But, at one time, the Hibernate developers created Hibernate Tools that contained a tool that would generate your classes from the hbm.xml file as well as the Data Definition Language for the database. These were originally built for Ant, but now most of Hibernate has switched to Maven, which its self seems to have its own learning curve and complexities. The bonus side is that it will automatically use the Maven repository. Thus, I am curious how to make the Hibernate Tools work with Maven, the same way they work in the Harnessing Hibernate book by James Elliot et al. The great thing is that the from the hbm.xml file, one can generate .java files using hbm2java and the database definitions using hbm2ddl. I find this way very interesting, as the hbm.xml already describes the .java and the data definition. The trick is making them work in Maven.

Posted in Hibernate | Comments Off on Getting Started