Posts Tagged “Java”

hibernate logo
So this has been a long time coming. I’ve put it off time and time again because there was just so much area I wanted to cover. (see previous post) So finally I’ve decided to cut a bunch of scope and just get this done.

This article is part 2 in a series of 3, which I started way back in November. The project herein is a continuation of that project and the updated project files are included here. I won’t be covering the additional Maven issues in hopes that the first article brought you (the reader) up to speed on those. I will say there are some additional dependencies, so it would be best to use the new files and update your eclipse project files by running the eclipse:eclipse target with Maven.

Hibernate

Hibernate is a great tool. It makes my life easier, and that is good. It started out as a Java only technology. After checking the website it appears they have a .NET version too. Hibernate is a persistence manager. Well you say, “Whatever does that mean?” Well it means that I can map my objects to a set of tables and Hibernate will manage their persistence. Hibernate is language agnostic. For the most part you just tell it what database dialect to use and unless you are using some special features not supported by other databases you can pick a code base up and move it from one DB to another with no change. Another great thing about hibernate is its ability to load an entire object graph, eagerly or lazily, just from querying a single object. For instance let’s say you have a person object, and that person has an address object on it (or even several). Issuing a query for that person will automatically load the address. (For lazy loading it will actually proxy the object and then retrieve the address when the getter is called but that is beyond the scope of the project, yet again, so I won’t go there.) And the last big plus Hibernate brings you, all of this being in my opinion, is updating and keeping object references the same for objects which should be the same and are loaded in 2 different places. Imagine doing all of this in straight JDBC, yuck, I don’t even want to think about that.

Let’s get started!

First things first, download and install MySql, my favorite database. Once you have it all installed, create a user, you can name it whatever you like but I choose test, with a password of… password. If you stray from these values you’ll want to change the configuration that we’ll talk about later. For administrating MySql, if you’re not comfortable with the command line, which I admit can be a bit daunting with a DBMS, then I suggest you also install the MySql GUI tools, they are great and work for Windows, Mac, and Linux. After creating the user, also create a database, again I would call it test, and give the user permissions to access it. I had hoped to do this all using an in memory DB like Derby or Hypersonic, but again out of scope.

The next thing you want to do is to execute the DDL I’ve prepared which is in the application’s src/main/resources/ directory. Creatively enough it’s titled DDL.sql. It’s important for me to note that Hibernate can create this file for you based on either your mapping files or your annotations (more on these later), but again it was out of the scope so I went ahead and prepared one for you.

Down to the nitty gritty.

Now our database is set up and we are ready to get going. First thing’s first, we need to tell spring where our data source is and where does our database server live. It won’t always be localhost, in fact most of the time it shouldn’t be. So we are going to create a datasource bean using spring, which we will later provide to our DAO’s for use with Hibernate. For defining our data source we have several options. I hopefully have chosen the simplest one, which is to declare an instance of spring’s DriverManagerDataSource bean in the spring-web-config.xml file like so…

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost:3306/test</value></property>
<property name="username"><value>test</value></property>
<property name="password"><value>password</value></property>
</bean>

This is the code block you will want to pay attention to if you have used a different username/password than I did. So what is this doing for us? Well this is telling spring to instantiate an object that is a DriverManagerDataSource. On that object it is setting 4 parameters; the JDBC driver to use, the location of the database, the username, and of course the password. Later we will use this bean in our DAO’s so that they can connect to the database. Alternatively we could have used JNDI to locate a defined data source which lives most likely in a server config out there somewhere, but this is out of the scope for what I want to accomplish.

The next thing we need to do is to set up the session factory in our DAO config. We are going to configure our DAO using a file called spring-dao.xml. We load this file in the web.xml file in the context config section.

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="batch_size">15</prop>
<prop key="fetch_size">30</prop>
<prop key="hbm2ddl.auto">false</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>

<property name="dataSource">
<ref bean="dataSource" />
</property>

<property name="annotatedClasses">
<list>
<value>com.weneck.webapplication.domain.Game</value>
</list>
</property>
</bean>

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>

This does a few things for us. First are the Hibernate properties. We tell Hibernate what dialect to use, some parameters on how to batch queries, and if it should show the SQL being used. After all, Hibernate does still use SQL to communicate with the DB and these statements can be a great way to debug or just learn. Next, we provide the datasource. Remember that datasource bean we just defined, her is where we are using it. Additionally we have a transaction manager, and the location of our annotated classes. For now we only have 1 annotated class in hopes at keeping this simple. Finally we are going to want to set up our JDBC template for our JDBC counterpart. I’ve included a duplicate DAO which uses JDBC instead of hibernate to illustrate the differences.

Domain what?

Lets model our domain. I’m sure by now, especially after applying the DDL you have guessed our domain is a simple object representing a video game. Now we need to model our object in the java world. Take a look at Game.java. At its heart Game has 4 attributes; id, title, platform, and description. What isn’t as clear, perhaps are the annotations marking up the class everywhere. These are JPA standard annotations, which are compatible with Hibernate and tells hibernate what to do with these objects. Let’s take a closer look.

  • @Entity – this tells hibernate that this class should be considered an entity. Easy enough right?
  • @Table(name=’games’) – this tells hibernate what table in the database this entity maps too, still easy.
  • @Id – This tells hibernate that this column/attribute should be considered the primary key of the entity. For composite primary keys you should take a look at the documentation for @EmbeddedId and @Embeddable.
  • @GeneratedValue(strategy=GenerationType.IDENTITY) – this is perhaps a more vague annotations, in our case MySql supports auto_increment, this is a good thing, it means that objects inserted will automatically receive the next value for their id column. Other languages (*cough* I’m looking at you Oracle) do not support this, in that case you need to define a sequence, and tell Hibernate to use the sequence with @SequenceGenerator and a different strategy for the @GeneratedValue annotation. Man, I need to stay on topic.
  • @Column(name=”id”) – this is hopefully the easiest one to understand, what column in the table does this attribute map to.

There are a ton of other useful annotations, including adding constraints @NotNull, where clauses that are ever present @Where, and mapping @OneToOne, @ManyToOne, @OneToMany, and @ManyToMany relationships.

The DAO Layer

Next we need to write our DAO’s. As a general rule and a good practice, DAO’s should not contain any logic, but merely manage objects persistence to and from the database. This isn’t always possible, but something to think about when writing your DAOs. I’ve started by creating a GameDao.java interface. We want to be able to list all of our games, search our games, and save a game. So these are the 3 methods I’ve defined in my DAO. There is a JDBC implementation of this DAO in GameDaoJDBCImpl.java and a Hibernate implementation at GameDaoImpl.java. Once these are written we need to define them in the spring-dao.xml file, and provide them with the data source or the session factory depending on their implementation. Notice each DAO extends a different spring helper class for providing common functionality.

For the hibernate side there are a few important built in methods for managing your domain. Load and Get are good ones, simply call getHibernateTemplate().load(Class.class, Id); or getHibernateTemplate().get(Class.class, Id); specifying the class you want to load along with the primary key you specified with the @Id or @EmbeddedId anotations in the model class. That’s it, the object will come back, properly typed and everything. The loadAll method is similar but you need not specify an id and you get all the objects of the type Class.class. Save is pretty simple, though in my opinion should not be used. It takes an object and saves it. Easy! But it’s my preference to instead use saveOrUpdate, since this will save a new object or as the name suggest update an existing one, thusly killing two birds with one stone. Update, well, if you read that last sentence you know how I feel about update. Delete, pretty easy this one, it deletes the object.

Now we are getting to some of the fun methods. Find will return a typed list of object that meet the criteria supplied in the HQL statement. Whoah, HQL, what’s that? Well it’s nearly identical to SQL, only you can use the java entity name and attribute name of those entities instead of having to reference the column names directly. This includes automatically joining the attributes that might be joined into the entity using some of the @OneToOne etc… anotations. Last there is Execute. It again does as it says, will execute a statement, usually a ddl statement tough it doesn’t have to be.

Spring Services

Normally here is where I would tell you to create your services, configure them in the spring-service.xml file, and put any logic in these classes. In this simple example however, we aren’t really coding any logic, so we’ll bypass this important layer of the web application.

The Results

Fire up that server and open a browser to http://localhost:8080/WebApplication/test/

Just for funzies I’ve included a JDBC implementation for comparison. If you look in the TestServlet.init() method on line 28, you can toggle the comment to use this implementation instead. Such a contrite example it doesn’t showcase all the greatness that Hibernate is, but with a little imagination I bet you can see your way through to the possibilities.

Next up…the whole reason for starting this series, Spring 3 MVC. It’s gonna be a good’un.

Comments No Comments »

Maven

What it is and what it isn’t

Maven is first and probably most agreed on by developers a dependency manager. Public repositories all over the net house project dependencies, as well as files called poms which contain descriptors of other files that the dependency is dependent on. As a dev this can be quite a time saver so that all dependencies are downloaded and placed on the class path instead of manually downloading 1, finding out what jars its missing, then downloading those… so on and so forth.
Secondly maven is a build framework. Maven aims to be a constant for building any java project across all java projects. With a standard life cycle developers can become familiar with the framework and aim for a smoother build process. In order to do this Maven needs to be extend-able. Good thing it is. Maven has oodles of plug-ins for near any task for the build process. Plug-ins can (obviously) build java code, run ant tasks, run automated testing, run sql code, run code coverage reports, deploy artifacts (to a repository or a server), exec os code, pretty much the sky is the limit.

Installation.

Installing maven is not a complicated process but many get confused with it, mostly because of setting the proper environmental variables. First make sure you have java properly installed and the JAVA_HOME environmental variables properly set. Then download the latest version of Maven from http://maven.apache.org/download.html and unzip it wherever you please. From here you need to add a few environmental variables and add maven to the system path.

For Windows

Control Panel > System > Advanced > Environmental Variables
Under the system variables list add a new variable
MAVEN_HOME = C:\... (maven install location)
and append this to your path
;%MAVEN_HOME%bin\

For *nix

export M2_HOME=(Maven install location)
export M2=$M2_HOME/bin
PATH=$PATH:$M2

now at the command line you should be able to type
mvn --version
and get some kind of output like this…
Maven version: 2.0.9
Java version: 1.6.0_11
OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows"

How it works.

Maven uses a file called the POM (http://en.wikipedia.org/wiki/Project_Object_Model#Project_Object_Model), short for project object model. This is an XML file that describes your project. Here you can list what the name of your project is, what is its version, how it is packaged, how it is built, repositories for any dependencies, and last but not least its dependencies. There are many advanced configurations such as specifying profiles that are beyond the scope and necessity of this entry to go into.
Lets dig in shall we?

< ?xml version="1.0" encoding="utf-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelversion>4.0.0</modelversion>
<groupid>com.weneck.webapplication</groupid>
<artifactid>WebApplication</artifactid>
<packaging>war</packaging>
<version>1.0</version>
<name>Sample Maven Webapp</name>
<url>http://maven.apache.org</url>
...
</project>

The pom starts out simple enough, you have your XML encoding and versioning information, project declaration and schema information. The modelVersion declared what version of the POM we are using, in this case 4.0.0, not to be confused with the version of your project. Next is the group id of your organization, the name of your artifact (artifactId), how your artifact should be packaged, in this case a WAR file (http://en.wikipedia.org/wiki/WAR_%28Sun_file_format%29). Finally a name and a version number of your artifact should be declared. Simple enough eh?

<repositories>
<repository>
<id>springsource maven repo</id>
<url>http://maven.springframework.org/milestone</url>
</repository>
</repositories>

The next section defines your repositories. Kinda like how it reads. In this case we are specifying springsource’s milestone repository so we can grab the Spring 3 RC artifacts (important for the final segment in this piece). You can also specify these in your settings.xml file locates in the maven home directory. This is usually ~/.m2/ or %USER_HOME%/.m2 depending on your OS.

<build>
<finalname>WebApplication</finalname>
<plugins>
<plugin>
....
</plugin></plugins></build>

The build section is next, here we define the plugins we are going to user, most commonly the compiler plugin, a properties file plugin if needed, and if you’re using eclipse (you should be) the maven-eclipse plugin. (fear not, full source attached at the end of my rant.

<dependencies>
<dependency>
<groupid>javax.servlet</groupid>
<artifactid>jstl</artifactid>
<version>1.1.2</version>
</dependency>
...
</dependencies>

And finally the dependencies section. Here we define each of the dependencies our project is… well… dependent on. Easy peasy huh?

Now the cool part, putting it all together. So there is a common file structure maven expects, as well as few file we need to put in place for this thing to get off the groung. They are all included in the source, but I’ll gloss over them here. Maven expects a src folder with 2 folders within it, main and test. It’s not rocket science, as the names suggest you source code goes here. Inside the main folder goes your main files, and inside the test folder all files associated with your testing process/procedures. (you are testing your code right?) Inside main you have java, resources, and webapp. Inside java is your java code, resources is your resources, and webapp are the files needed for a webapp. Am I sounding redundant here? I also stuck in a nearly blank jsp for good measure. Hey, when its all done we want to see something other than a 404, amiright?

Using Maven

You can use maven from within eclipse, which used to work really well, but last time I tried was kinda buggy and bothersome. So I prefer the command line. First things first we need to configure eclipse to use all these wonderful dependencies that maven is managing for you.
mvn eclipse:eclipse
This line will download all your dependencies into that .m2 folder I referenced earlier. It will also write a .project and .classpath file for eclipse’s benefit. This will point java’s build path within eclipse to those dependencies which are not being stored within your project. Be sure to refresh the workspace after performing this command as eclipse does not activley monitor those files and will continue to complain about missing dependencies untill you do so.
mvn clean
This wonderful command performs a clean on your project, simple.
mvn install
Here’s our meat and potatoes. This command does what we really came here for. It creates the target directory structure, builds our code, and packages it all into our pre-defined package structure. In our case the war file. It also puts all the structure in place for eclipse’s WTP so if you have a java server configured in eclipse you can now add the project to the servers hosted projects. (Once added to the web server you dont need to continually build with maven, you can build with eclipse and WTP will pick up the changes and replace the necessary files in the web-server or prompt you for a restart.)
You can also chain these command together.
mvn clean install
That about wraps it up for Maven, but stay tuned for the next segment, Hibernate.

As promised Source

Comments 1 Comment »

So I’ve decided to take the plunge. After seeing a friend/colleague of mine launch his own company SendAlong I’ve began the workings for an idea I’ve had for a long time.

I intend to create an evaluation software, targeted toward the Educational market for online professor/course evaluations. Its an idea thats been buzzing around in my head for a long time, actually a result of an earlier need from the IMS department at Miami University. Years ago I wrote a juvenile application which had a static form and recorded results of that survey into a database. It could then retrieve them and perform simplistic analytics on the results. It has had a long life for how simplistic it was and how naive I was at the time of writing it. The admin interface even had my first delve into AJAX and as a result only worked in Firefox.

Day 1 is complete, and the database is vaguely designed. 32 tables so far, short of my work at DARS perhaps the most complicated database I’ve ever interfaced with. Requirements are also starting to shape up. My biggest debate of the day was how large scale this application would reach. If it were going to be a smaller application, with limited functionality, which was my original intent, I was leaning toward a PHP application. However after considering the scale of my ideas, and my desire to re-acquaint myself with SPRING I decided to work toward a J2EE application. This will allow for bigger scaling and hopefully more value. I know I say I know SPRING on my resume, but while starting this project I’m hitting a learning curve. I know how to work in an existing SPRING environment, and do some complicated web flows and database transactions, with the help of Hibernate. However, I have never been present at the conception of a project which required setting up that working environment. I guess I have my work cut out for me but I’m sure it will happen.

Comments No Comments »