Converting a Java Project to Use JPA

In this post I walk through some of the gotchas when converting a java application that works with raw SQL strings to one using ORM (Object Relational Mapping) via JPA (Java Persistence API). I will be converting a simple application from “Generic Java GUI Netbeans Project with Embedded Database” that only has 2 entities: Post and Comment.

The finished product is in a git branch called JPA. If you don’t use git you can download this sample project as a zip from MediaFire.

You can view all the changes to convert to JPA in this Github diff.

Netbeans makes the initial setup very simple by generating persistence.xml (you find the persistence unit name here) for you, as well as the the entities for you from your database.

SQL needs to be rewritten to Java Persistence Query Language

This isn’t much an issue really; in the long run it does you a favour since it is database vendor independent.

Change from:

ResultSet rs = db.executeQuery("SELECT * FROM post ORDER BY date_created DESC");


List<Post> rs = db.createQuery("SELECT p FROM Post p ORDER BY p.dateCreated DESC").getResultList();

Default Values are Lost

I noticed something strange when adding a Post entity: the created_date attribute shows up as a null when I convert to use JPA. My DDL (Database Definition Language) looks like this (Derby DB SQL):

    name VARCHAR(250) NOT NULL,
    content VARCHAR(500),

So each time I create a Post, I’m expecting the date_created attribute to show the current date, but it doesn’t. So all the SQL code where I have DEFAULT is basically replaced with null when I use JPA.


The workaround is to code the default values into the attribute field of the entity classes. Here is the dateCreated attribute inside Post:

@Column(name = "DATE_CREATED")
private Date dateCreated = new Date(); // new Date() returns the current timestamp

Exceptions in JPA Only Happen in Runtime

So when converting the code, I realized that in the places where SQLException would appear, Netbeans puts up an error saying that SQLException doesn’t happen here:

Sqlexception is never thrown

That’s ok I think. But what’s weird was that it offered to remove the try-catch block as a solution! Wow wow wow, stop. Aren’t there exceptions? Well, turns out there’s PersistenceException.

The problem? It’s a subclass of RuntimeException. I don’t exactly know what was the reason the exception was happening in runtime, but without the try-catch block, the procedure is going to fail (Here the Post entity cannot have null value for Name attribute) silently.

Now for a before and after. Before:

String sql = "INSERT INTO post (name, title, content) VALUES (?, ?, ?)";
try {
    PreparedStatement ps = core.DB.getInstance().getPreparedStatement(sql);
    ps.setString(1, authorField.getText());
    ps.setString(2, titleField.getText());
    ps.setString(3, postTxtArea.getText());
    JOptionPane.showMessageDialog(this, "Post has successfully been added.", "Successfully added post!", JOptionPane.INFORMATION_MESSAGE);
    dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
} catch (SQLException ex) {
    JOptionPane.showMessageDialog(this, ex.toString(), "Invalid content... or some shit like that", JOptionPane.ERROR_MESSAGE);


try {
    Post p = new Post();
    JOptionPane.showMessageDialog(this, "Post has successfully been added.", "Successfully added post!", JOptionPane.INFORMATION_MESSAGE);
    dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
} catch (PersistenceException ex) {
    JOptionPane.showMessageDialog(this, ex.toString(), "Invalid content... or some shit like that", JOptionPane.ERROR_MESSAGE);

The following dialog should pop up when the Author field is empty:


Well, this output doesn’t just happen automatically. There’s still one more issue that I’ll get to next:

Empty Strings are not Null

In my DDL, I have a rule that Post cannot have null value for Name attribute. Yet for some reason a string “” is not a null value in JPA. It is actually stored in the database as “”.

How is “” not null?

stored as empty string

This kind of shit doesn’t happen when simply working with raw SQL strings.

There are workarounds for this online: one of them was using the annotations @Size(min=1) or @NotNull. Unfortunately I’m using Java SE 8 (@Size is currently supported up to Java EE 7 as of this writing) and I’m not using Spring (for @NotNull).

So what I ended up doing was place the validation in the setter method:

public void setName(String name) {
    if (name.trim().isEmpty()) return; // empty strings begone! = name;

As you can imagine, I have to do this for every attribute in every entity that doesn’t accept empty strings.

You Need to Manually Manage One To Many Relationships

I had this issue that when I add a one to many relationship: Post has many Comments, now I add a Comment to a Post. I don’t see the changes immediately though; had to restart the application to see the new Comments. I would have thought that JPA would update the Comments collection inside the Post, but it didn’t.

Here’s how my setPostId function in my Comment entity looks like:

public void setPostId(Post postId) {
    this.postId = postId;

This is because (as aggravating as it sounds) in JPA, it is the responsibility of the application, or the object model to maintain relationships. By that it meant that it is the responsibility of the programmer to manually code in the links when a setter is called:

public void setPostId(Post postId) {
    this.postId = postId;
    postId.getCommentCollection().add(this); // programmer needs to add this himself

I’m going to be a bit honest here: this is kinda inconvenient, and retarded. In Rails this sort of things is done automatically, and it should be. In JPA I need to remind myself that each time I have a one-to-many relationship I need to manually link them together or it doesn’t update automatically/only updates after application is restarted.


There may be other quirks I may miss out since I’m only dealing with a very simple project that doesn’t even have update and delete, so feel free to let me know about in the comments below.

Yea, I know I complain a bit, but working with raw SQL strings is going to be pretty hard to manage in the long run. You’re dealing with simply strings, most errors only pop up in runtime, and your IDE can’t assist you much. With JPA when you’re writing in Java Persistence Language, Netbeans can actually figure out data types and attribute names:

autocomplete in java persistence language string

So unless you really need that sort of performance boost, using an ORM would be the right call.


Generic Java GUI Netbeans Project with Embedded Database

So your team just wants to create a java GUI project that requires a database. How do you minimize the hassle of configuring a database? For this reason I created this simple generic Micropost project to serve as a template to start out.

Link to Project:

2015-11-30 15_48_30-New notification

This guide requires that you are already familiar with SQL and java GUI development.

Configuration and Setup

The only thing you need to run this project is Netbeans. Download the ZIP folder from the site, or git clone the repo if you know git. From there, you open up the project from Netbeans and click run.

That’s it.

Did I mention configuration? There is zero configuration. Even when you deploy your application as a JAR file, it is the same thing; it runs automatically. Just like that.

Prerequisite Knowledge

You need to understand a few things:

  1. Embedded databases
  2. Migrations

Embedded Database

An embedded database is a database that do not need a server, and is embedded in an application. This means the application itself manages the database directly. Here, I am using Derby DB (or Java DB). JDK comes prepackaged with this, though to avoid trouble I have packaged that library into the project itself.


Notice, that when you launch the application a folder called “database” and a text file “derby.log” is created. These are the files you will remove should you want to start clean.

You can view the schema and data in the “database” folder from Netbeans. Under the services tab, right click on Databases and select New Connection…

netbeans new connection

Select Java DB (Embedded) as the JDBC driver and click next. Where you see JDBC URL, append the directory of the database folder. Leave the User Name and Password field blank. Click Test Connection and it should indicate “Connection Succeeded”.


Then click Next until you cannot click it anymore, followed by Finish. Now you can peep inside your embedded database, and execute queries as you please:

netbeans database service

IMPORTANT NOTE: Derby DB embedded does not support multiple connections at once. If you connect to the database via Netbeans database service, then you can’t run your application. You have do disconnect (right-click the connection and disconnect it) from the database first before running your application again.


When you first create your database, you don’t always figure every possible entities and relationships in one shot. Inevitably, we would want to make incremental changes to add remove tables or modify existing tables, migrating the database to a different version. Chances are also that you don’t want to wipe out your existing data because of it. This is why migrations are created.


This project uses Flyway migration library. It is as simple as just using a series of SQL files with the prefix V1__blablabla.sql, V2__blablabla.sql and so on. These SQL files are then executed in that order. Therefore, when you make changes to your database, you simply add another migration file (or you can just modify a single migration and wipe out the database every time). If you are working together using a VC system like git, all your databases will be synchronized automatically to the latest structure with existing data intact.

Migrations are located in PROJECT_DIR/src/db/migrations:

2015-12-04 14_46_55-Search

Each time the application is launched, it automatically migrates the database to the latest version.

That is all you need to know. For everything else go figure on your own. Good luck!

Ninja Framework Tutorial – PART 3: Connect and Migrate a Database (H2, MySQL)

This a part of a series of tutorials on Ninja Framework. You can click here to see the full set.


I’ll talk a bit about the built-in embedded H2 database, followed by how to setup and connect to a MySQL database. Though this guide is specific to MySQL, you can apply the same thing to other database vendors as well.


I initially thought of starting off from the previous tutorial, but couldn’t get the persistence.xml thingy to work (I’ll get to that later). I concluded that it’s easier to just start from a template that is already connected to a database. So to start off, create a maven project as prescribed in the first part of my tutorial, but instead of choosing the “ninja-servlet-archetype-simple” in the “New Project” step, pick  the “ninja-servlet-jpa-blog-archetype”. The setup procedures after that remain the same.

2015-04-23 23_01_55-Home page

And then you just run it! It just works right off the bat – a blog website example in which you can add blog posts but can’t delete or modify what you create – without needing to start any database service. This had me puzzled for awhile since I actually didn’t know something called “embedded databases” at that time.

H2 Embedded Database

You should go through this while reading Ninja Framework’s JPA guide.

An embedded database is simply a database that is tied directly with the application itself; it’s like a part of the application itself instead being some separate thing that you have to run separately. That’s why you didn’t have to run the H2 server and the website runs fine.

The database itself is actually stored in “PROJECT_DIR/target”. The *.mv.db files, which were created at first run, contains all that table data. To access them you could download a stable release of H2 database and run the H2 console with the help of this guide.

In the JDBC URL you have to set the full file path of the database file, without the *.mv.db extension:

jdbc:h2:E:/Documents/Web Dev/NinjaPlayground/target/h2database

Take note that the username is “ra” instead of the default “sa” you saw on the quickstart guide. Details of this is in the “PROJECT_DIR/src/main/java/conf/application.conf” file:


The dot(“.”) points to your project directory. So anyways now you can manage your database outside your website.

2015-04-23 23_27_20-H2 Console

Note that due to the nature of embedded databases, you can’t access the database from the H2 console and access from your website at the same time. You can try logging in to the site and it’ll return a 500 error (you’ll have to wait a while for it to show up).

In-memory Database

In-memory database is what it say it is: it’s a database running in your RAM, and it’s bloody fast. Why would you want to use it? Well, mock testing your database models would be a good one. If you noticed, your site was actually doing some testing procedures when (in fact Ninja Framework makes a big deal about tests) you execute “Clean and Build”. Right now the tests use an embedded database, but you can easily change it to be in-memory for a speed boost. Simply change the JDBC connection string from:




The “DB_CLOSE_DELAY=-1” option just prevents H2 from wiping clean the database when a connection closes; it waits for the JVM to stop running before doing so. So now running the tests each time your database is a clean slate. You can test this out by right-click your project and select “Test”. The tests will all pass, yet there was no database file created.

2015-04-24 00_33_13-ninjaBlog - NetBeans IDE 8.0.2

I won’t be going through TDD (Test Driven Development) in this series, but is a great place to know what it is. I’d highly recommend you understand what it is as it would likely improve the quality of the software you write.

How is All of this Working?

First off you need to understand that your Ninja website doesn’t just know how to understand H2 on it’s own. It uses the Java Database Connectivity (JDBC) API interface layer to access your database, and you need a JDBC compliant driver that implements this interface layer to enable this interface to talk your database.

I’m not talking sense? Well, simply put, all you need to know is that JDBC enables you to talk to a broad variety of different tabular databases (and there are a lot of them) in a consistent manner regardless of how the database is implemented. Just select the type of database you want; in this case you add the driver to your pom.xml. Therefore you’ll find this piece of code:


Yea – the power of Maven! You don’t even have to download and install the driver yourself. After that you’ll have to configure the database in the application.conf as explained earlier. Now notice the line:

ninja.jpa.persistence_unit_name = h2

This “h2” maps to a persistence unit inside of “WEB-INF/persistence.xml”. By default entering the file Netbeans will show you the “Design” view – it never really seems to work properly though, so I’d suggest going to source view (like how real programmers roll):

2015-04-24 00_09_23-ninjaBlogStart - NetBeans IDE 8.0.2

Ok – this file is important – but only few things are important. So when you check out the persistence-unit name with “h2”, pay attention to these few options, cause we’ll need to understand them before configuring the MySQL equivalent:

<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />

For every different database these 2 lines will guaranteed need to be changed. Frankly I’m not so sure where to find a one place that contains every configuration for persistence.xml there, but you can find a list of dialects here. Aside that I guess googling something like “persistence.xml hibernate mysql” would work (which was what I did).

Another 2 lines you should check out is this:

<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />

Turning those on (set to true) will output every single SQL query in your output window (which I never bother to look at; it clogs up my output window). If you find that useful for debugging in dev mode by all means turn it on. You’d probably want to turn it off when you deploy your application though.

And that’s it! It’s that simple right? Add the driver, setup the configuration and put stuff inside persistence.xml. Glorious.

Let’s Connect to MySQL!

Ok! Now we put the pieces together. I assume that if you already wanted to connect to MySQL you’d know how to setup the database server. Since I’m in Windows, I will be using XAMPP since it has everything built in (even stuff you’d probably never use in your life). So make sure your MySQL database server is running (it would default to use port 3306 unless you change it) and also run Apache since PHPMyAdmin uses it.

2015-04-24 00_30_39-XAMPP Control Panel v3.2.1   [ Compiled_ May 7th 2013 ]

Now in pom.xml, same place where the H2 dependency XML node is placed, add this piece of code:


I actually just found this by googling “mysql maven dependency” and this link was the first to pop up. You should be able to find drivers for SQL Server or IBM DB2 the same way I guess.

Now you tweak the settings in you application.conf: = true
ninja.jpa.persistence_unit_name = mysql


You should make sure that “acooldbname” actually exists this time; server mode databases don’t get created themselves at runtime like embedded databases.

“root” is the default username for MySQL, though it’s good practice that you setup each database with its unique username and a secure password. Personally I don’t bother with this in a dev environment, but in production you should.

But wait… what if we can do both? Ninja has predefined modes that makes it convenient to do this (click here to read about configuration and modes in Ninja): = true = mysql


Just in case you need a refresher:

If no mode is set explicitly Ninja will use the prod mode. That means if you deploy Ninja via a war file to an arbitrary servlet container Ninja will use the prod mode. Ninja’s SuperDevMode will set the mode to dev. And Ninja’s testcases will use mode test by default.

Now, if you’re wondering why is there a “”, I’ll get to that shortly.


As discussed prior, you’ll have to add some XML configuration thing to your persistence.xml:

<persistence-unit name="mysql" transaction-type="RESOURCE_LOCAL">

    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

    <property name="hibernate.show_sql" value="false" />
    <property name="hibernate.format_sql" value="false" /> 

    <!-- Connection Pooling settings -->
    <property name="hibernate.connection.provider_class"
    value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />

    <property name="hibernate.c3p0.max_size" value="100" />
    <property name="hibernate.c3p0.min_size" value="0" />
    <property name="hibernate.c3p0.acquire_increment" value="1" />
    <property name="hibernate.c3p0.idle_test_period" value="300" />
    <property name="hibernate.c3p0.max_statements" value="0" />
    <property name="hibernate.c3p0.timeout" value="100" />

And running it now will give you failures!

Introducing… Database Migration

Wow what? It was working just now! But how do you think the database just magically appeared with all the data inside? This is the magic of database migration built in to Ninja Framework with Flyway. Moving your database from development to production is now as simple as moving it together with your website, add a database with the right specifications and configurations, and it will be populated with tables at first run. Database migration, though, takes it another step by also doing “version control” with your databases. That means you can incrementally modify your database (what database continues to stay the same after initial deployment anyway?) with your site. Flyway keeps track of this by adding a separate table to your database called “schema_version”. However, Flyway doesn’t allow you to downgrade changes like Rails or Laravel.

So that’s all cool and all, but it doesn’t explain why it failed. To solve this, check out the “V1__.sql” (it’s recommended you follow their naming convention) file under “db/migration”. As of this writing it looks like this:

-- the first script for migration
create table Article (
 id bigint generated by default as identity,
 content varchar(5000),
 postedAt timestamp,
 title varchar(255),
 primary key (id)

create table Article_authorIds (
 Article_id bigint not null,
 authorIds bigint

create table User (
 id bigint generated by default as identity,
 fullname varchar(255),
 isAdmin boolean not null,
 password varchar(255),
 username varchar(255),
 primary key (id)

alter table Article_authorIds
add constraint FK_f9ivk719aqb0rqd8my08loev7
foreign key (Article_id)
references Article;

Therein lies another limitation of Flyway: your migration is specific to one database vendor only, since SQL is a little different from one database to another.

Well, you can say this is shitty, but chances of you jumping from one database to another is pretty rare (I think), so let’s take it that being stuck with just MySQL is not a bad thing.

So now you change the SQL syntax to be complaint with MySQL:

-- the first script for migration
 content varchar(5000),
 postedAt timestamp,
 title varchar(255)

CREATE TABLE Article_authorIds (
 Article_id bigint UNSIGNED not null,
 authorIds bigint UNSIGNED

 fullname varchar(255),
 isAdmin boolean not null,
 password varchar(255),
 username varchar(255)

ALTER TABLE Article_authorIds
add foreign key (Article_id)
references Article(id);

So now (fingers crossed) you should be able to run the blog example using MySQL! You’ll see the table created with data added inside. The SQL migration however, didn’t insert any data to the database; you can change what gets added in “dao/” – that piece of code, is database vendor independent. I will not be going through that code for this part of the tutorial though.

Anyways, here’s the tables inside PHPMyAdmin:

2015-04-24 10_00_47-localhost _ _ ninjadb _ phpMyAdmin

Hey wait a minute! What about the tests? They’re still using H2 database aren’t they? Yet if you run them now it’s still working! H2 tries to be compatible with other databases. In fact, it also has compatibility modes to mimic other database vendors (Read their documentation for instructions on how to configure that) but… when I added a “MODE=MySQL” the whole thing just flops so… up to you to decide whether having 2 database vendors in one project is a good idea or not I guess.

Adding a Migration

Now I noticed something about the “article_authorids” junction/bridge/join/map/linking/intersection table: there is a foreign key constraint on one side linking the primary key in the “article” table, but none for the “user” table (by the way you should come up with more obvious names for junction tables than the one in this example).

So let’s make that change now. Add a V3__.sql file alongside the other migration files:

ALTER TABLE Article_authorIds
add foreign key (authorIds)
references user(id);

But hey – V2__.sql is empty! Why don’t we just change that instead? Well, although it is empty it has already been executed (schema_version table):

2015-04-24 10_38_24-localhost _ _ ninjadb _ schema_version _ phpMyAdmin

If you insist, you could remove the V2__.sql entry and run your project again. Honestly I would just wipe out the whole database just to be safe.

Note that rollback of changes in the even that a migration failed is not supported in every database. It is therefore recommended you test your migration SQL in PHPMyAdmin and make sure it works before adding it to your project. If crap happens there you could just wipe out your database and run your project again.

So there you go! The foreign keys are working properly now.


That is enough for part 3 (phew)! I congratulate you for making it this far (:. Next part I’ll be walking through some Java code in building a basic CRUD website.

Ninja Framework Tutorial – PART 1: Setting up Ninja with Netbeans

This a part of a series of tutorials on Ninja Framework. You can click here to see the full set.


For the first part, I will walk you through how to get a Ninja site running with Netbeans. The end product is as simple as just launching Netbeans and hit Run Project. No command line needed. As of this writing these are the current versions of what I’ll be using:

  • JDK 1.7.0_25
  • Apache Maven 3.3.1
  • Ninja Framework 5.1.0
  • Netbeans 8.0.2

Brief Intro

(You can skip this section if you want.)

Lately I’ve been looking into web development with Java. As with general web development, working with simply just raw java is tedious and prone to lead to a ton of bad practices and lots of unnecessary code. Why reinvent the wheel? Having experience with Laravel, I decided using a framework would be a sensible choice. After choosing between Spring MVC and Ninja, I opt for Ninja.

Reasons for my choice is besides the point for this post; chances are if you are here you have already decided to use Ninja over a dozen other Java web development frameworks.

Why write a series of tutorials? The Ninja Framework website is pretty nicely documented, but I feel things could be simpler, and there are some holes that unless you’ve some experience you’re going to be a lost. In addition I don’t see many tutorials written about it. Everybody in YouTube land is doing more Ruby and PHP. When I searched “Ninja framework” in YouTube, all I found is an hour long video. Even in Google search I barely found anything useful.

Let’s Start!

First off, I’m assuming you’re going to start with nothing. I’m using Windows 8.1, but you should be able to apply it to Linux or whatnot. Following this guide, you first install JDK and Maven, followed by Netbeans (If you’re sure which edition, just choose all! XD). JDK and Netbeans is fairly straight forward so I won’t guide you through.

Maven is a little tricky. It’s not like you download some installer and you’re on your way. Netbeans does come with Maven built in, but currently it is using 3.0.6 whereas Ninja requires 3.1.0 and above.

What you have to do, is download the binary zip from the Maven website, extract the contents to your C drive. You will see a folder “apache-maven-3.3.1” or something like that in the root of your C drive. Rename this folder to “mvn” to make things simpler.

Add “C:\mvn\bin” directory to your environment PATHs so you access the “mvn” command in your command prompt. If you see some JAVA_HOME error when typing “mvn -version” in command prompt, add a environment user variable JAVA_HOME pointing to JDK:

2015-04-19 16_49_53-Environment Variables

If you’re not sure how to add an environment PATH or user variable, google it (lol).

Replace Bundled Maven in Netbeans

In Netbeans, go to Tools > Options.

Under “Java”, click the “Maven” tab. In “Maven Home” combobox, choose “C:\mvn”.

2015-04-19 16_54_14-Options

Now comes a catch: It doesn’t work! Netbeans is looking for a “mvn.bat” file in “C:\mvn\bin” which doesn’t exist…

Or does it?

It does, but named “mvn.cmd” for some reason. So the fix is simple: make a copy of “mvn.cmd” and rename it to “mvn.bat”.

Create New Ninja Project in Netbeans

So you saw the guide on how to create your first Ninja application right? This section follows just that. You can use command prompt if you like; I just thought it’s simpler to go through Netbeans.

Select “New Project…” icon in Netbeans. Under Categories, select “Maven”, and under Projects, select “Project from Archetype”. When you click Next, you’ll see a list of “Known Archetypes”. You can filter the result using the search bar, typing “ninja”.

2015-04-19 17_06_21-New Project


Choose “ninja-servlet-archetype-simple”. Lastly give your project a name and you’re finished creating your project!

Then, for first run right click your new Maven project and select “Clean and Build”. Wait a while and it should look like this:

2015-04-19 17_10_50-NetBeans IDE 8.0.2

If your project structure doesn’t look like this, right-click within the Projects window in NetBeans and from the “View Java Packages As” menu, you can now choose “Reduced Tree”. (

SuperDevMode via “Run Project”

SuperDevMode guide in Ninja’s website. For a first few days of using Ninja, I actually open up the command prompt, cd to the ninja project directory and copy paste “mvn ninja:run” every time I want to run SuperDevMode. When I want to terminate SuperDevMode I press “Ctrl-C” and type “y” to cancel batch process.

This is plain silly. Obviously IDEs are made to make this process simpler.

Right click your project and select “Properties”. Under Catergories, select “Actions”. Under Actions, select “Run Project”. Change the contents of “Execute Goals” from “package” to

ninja:run -Dninja.port=8080

2015-04-19 17_22_38-Project Properties - NinjaPlayground


You’ll see a new file called “nbactions.xml” added to your project. If you remove this file, it will revert back to the default “Run Project” settings in Maven.

 Port numbers VS Context Path

Why specify a port number you ask? Ninja Framework uses 8080 by default after all. But say you have multiple Ninja sites and you want yo run them at the same time. Distinguishing them is as simple as using different port numbers. You can then bookmark these in Chrome for convenient access.

But you can also use ContextPath like so, yes?

mvn ninja:run -Dninja.context=/your_context_path

Well, it gets the paths to your site screwed up. When I first did this the site was unable to find its assets (css, js files) because they were linked as such:

<script type="text/javascript" src="/assets/webjars/bootstrap/3.3.2/js/bootstrap.min.js"></script>

If your base URL changed from “localhost:8080” to “local:8080/your_context_path”, it still looks for the assets in “localhost:8080”. Therefore you have to retrieve your assets as such:

<script type="text/javascript" src="${contextPath}/assets/webjars/bootstrap/3.3.2/js/bootstrap.min.js"></script>

This is annoying for me to do, so I prefer to just change port numbers and give meaningful names via URL bookmarks.

 Ignore, I Don’t Want IDE Managed Deployment

Last step! (: Click “Run Project”. You’ll be presented with a dialog as below:

2015-04-19 17_41_45-NinjaPlayground - NetBeans IDE 8.0.2

Select “Ignore, I don’t want IDE managed deployment”, and SuperDevMode will now be running! Note that it won’t launch your browser automatically as other netbeans web projects; you’ll have to launch a browser manually and enter the URL “localhost:8080” (Not a big hassle I hope).

2015-04-19 18_33_34-Edit Post ‹ Bruceoutdoors Blog of Blots — WordPress

To turn off SuperDevMode, go to the Output window and click “Stop the currently executing build”:

2015-04-19 17_43_47-NinjaPlayground - NetBeans IDE 8.0.2


From now on, whenever you press “Run Project” (F6), it will execute SuperDevMode automatically. This will be specific only to this project. What a time saver!

Setup the Debugger

Follow the instructions under Debugging Under Netbeans from the Ninja Framework site:

  1. Right click your Project and open “Project”
  2. Click on “Action” on the left.
  3. Choose “Debug project”
  4. Enter “jetty:run” into the “Execute Goals” input field
  5. Enter “jpda.listen=maven” into the “Set Properties” field

This information will also go to your “nbactions.xml” file, as with how you set up “Project Run”. After that it is the same thing as running: you need to select “Ignore, I don’t want IDE managed deployment”. You’ll have to do this once, but afterwards you can use the dropdown shortcut:

2015-04-19 23_15_43-NinjaPlayground - NetBeans IDE 8.0.2

It will only use port 8080, so if you have SuperDevMode using port 8080 you should turn it off. Technically you can change this port number, but you’ll have to edit “pom.xml” and do configurations… which I despise; it’s not like ninja:run where you can specify it as a parameter. So therefore I will assume you’ll only debug one site at a time.

Technically you can debug one site using port 8080 and have 3 other ninja sites running on SuperDevMode (but using different port numbers) at the same time. Cool yes?

Bonus Section: Automatic Refreshing – Super Auto Refresh 

Workflow at this point is as follows: You make a change in Netbeans, Netbeans auto compiles for you, SuperDevMode picks up and changes and updates itself. You then refresh your browser to see the changes. The last step at this point is still done manually.

F5, F5, F5…

So to top it all up before closing, I wish to recommend another convenience tool called Super Auto Refresh. You can the Chrome extension via this link. Set the tab to your Ninja site for 2 seconds interval refresh and you’ll never have to manually refresh again! Of course, you could lag your PC doing this, so you shouldn’t try this if it slows you down.


That is all for part 1. In part 2 I talk about Adding CSS, Javascript Libraries using WebJars.

How I Failed a Basic Oracle Cert (1Z0-851) and What I Learned.

In MMU, there are a couple of certifications from industry titans like Oracle, Microsoft and Cisco that students can apply at a decent discount rate. Here’s Oracle Workforce Development Program (WDP) homepage:


The SL-275-SE6 code that was given there was a bit dated. It’s now called 1Z0-851 Java Standard Edition 6 Programmer Certified Professional.

Some of you probably heard of this course; the instructor went about sticking ads around the campus area. Well, I’ve taken the course and the exam it and here’s my review. Bear in mind I’m writing in the context of an MMU Foundation in IT student in the Cyberjaya campus, progressing to degree in the next October intake.

Disclaimer: If you are in foundation and have free time, DON’T TAKE THIS EXAM. I kid you not – it’s bloody tough, even for degree students you have went through OOP.

As a background I’ve already taken the Web Development Fundamentals (C#, ASP.NET) and Database Administration Fundamentals (SQL Server) exams from Microsoft under MMU in the same day, and aced them with >80% after just studying the night before the exam (passing mark is 70%). In addition, I’ve spent 6 months working as a PHP web developer in a startup.

My point from the above paragraph, is not to brag about how awesome I am, but to point out that I’m not exactly someone who is new to programming.

The difference from Microsoft and Oracle certs? Oracle may only need 61% to pass, but it’s twice as hard. Under MMU the Microsoft exams give you 2 chances (it’s not uncommon that people fail the 1st time) – if you fail Oracle’s test, you literally burn about RM330 (the amount you pay after a special discount) cash in the 2 and a half hours you sit down taking the exam (probably realizing how much you screwed up). That’s exactly what happened to me.

How did I prepared? I got “SCJP Sun Certified Programmer for Java 6 Exam 310-065” by Kathy Sierra and Bert Bates. Didn’t went through the 800+ pages book (I should have though); it has a CD which has 2 quizes and 2 mock papers (The mock papers are like the quizes, just without references and it has a timer).

I went through the powerpoint slides provided in the toolkit, then the 2 quizes with a friend for 2 days and took the mock a day before the actual test. Scored only 44% for the mock, but I went for the exam anyway, cause I was told that the book was magnitudes harder than the actual paper.

2014-10-09 22_38_10-MasterExam

Pretty good right?


cert result

I got so very SCREWED in the test center (I was nervous, my bladder was full, etc…), and scored only 41%; 20% short of passing, which was appalling. Yet in contrast for my preparation for the Microsoft certs, I studied a lot harder.

Here’s what I learned:

  • Just taking the training course alone guarantees 0% chance of passing.
  • Studying the powerpoint slides don’t get you very far. That alone will likely guarantee a high chance of failure.
  • The quizes from the SCJP Sun Certified Programmer for Java 6 Exam 310-065 are your salvation (though you should study the book properly), though they are slightly (only slightly) tougher (did I say slightly?)  than the actual paper. Make sure you score at least 60% without reference before you enter the test center.
  • You should also do some java projects from start to deployment, and if you come across something you don’t get, open up your editor/IDE and experiment. YOU NEED TO DO THIS. It’s not uncommon to find tricky questions on casting, autoboxing, and other strange (but valid) syntax.
  • In the quizes there are a variable number of selections for multiple choice questions. In the actual exam, they provide a fixed number of selections.
  • Regex came out. None of us thought it would but it did.
  • Dates and it’s formatting has a high chance of coming out. I had 2-3 questions, all of which I flopped (cause you have to memorize stuff).
  • Study threads meticulously; even go as far as memorize their methods. The questions I got mostly tests on code, as in whether it will work or fail, and if it works what is the possible output.
  • Know what “synchorized” means and how to use it.
  • You need to distinguish between abstract classes and interface, particularly in their syntax and usage (extends vs implements). It will definitely be tested; mostly in code.
  • A few questions asks about constructors, on execution order and how it is affected by polymorphism and inheritance.
  • static vs instance methods, and how they are affected in is-a relationships.
  • is-a and has-a relationships is guaranteed to come out, but that’s pretty easy.
  • Be fluent in using packages, and how to import classes and static methods through them.
  • For JAR you need to know how to compile and run and use them. One question even tests the JAR directory structure.
  • networking and GUI didn’t come out
  • you need to know what kind of exceptions will be thrown (like, memorize it!), and distinguish compile time and run time errors and predict which line causes the error.
  • By passing this course, you should be like some kind of human java compiler.
  • The finalize() method and how JVM manages garbage collection came out.
  • wrapper classes and their respective primitives also got come out.
  • terms like coupling and cohesion also got come out. None of us remembered what it was.
  • A question on case, default, break and how it leaks downwards is very likely to come out.

Did I regret taking this paper?

I’m not someone who’s trapped in regret, cussing my bad luck and my burnt RM330. It’s a bitter lesson, but serves me right I guess; I was pretty complacent towards this paper after how easy it was to score in Microsoft’s certs. I mean, it’s not even the advanced course yet y’know? 1Z0-851 is the very basic cert one has to take to proceed further.

Ironic, to think that just before taking the exam, I posted this status on my facebook:

2014-10-10 13_49_54-Lee Zhen Yong

It’s like I inadvertently predicted my own fall, like an oracle (get it? haha :D).

I do wished the lecturer would have made us more aware of the trenches we are suppose to expect though. Frankly most of us went through the training quite light heartedly.

Am I going to retake this paper?

Aw heck no. I was pro C++/C# to begin with anyway 😛