Site Sponsors:
Database + Java + NetBeans = Cooler-er 
It is Sunday … time to take a moment & share a few techniques!


This time-round, someone may like to learn how to use a database under NetBeans?

In-the-past we have shown how to persist data using everything from XML POJO Encoders / Decoders, CSV, and Hibernate. Under NetBeans, we have discovered that it's support for Java Persistence API (JPA) capabilities are second to none... once you know how to avoid a few common-sense pitfalls.

Case Study: The Quote For Today

I discovered several of those pitfalls last week: While migrating my 250,000 events, 180,000 community recipes, 250,000 personal recipes, and 80,000 quotations to Derby for this years effort to support “The Quote For Today”, rather than using Eclipse I opted instead to bring the blog up-to-date by using a database under NetBeans. Once created, a database can be used anywhere.

Getting Started

Of course, the first problem with using a database under NetBeans has to do with location: After we create a project using “New | Java Project | Java Application” from the main NetBeans Menu, how the heck do we add a database?

To demonstrate, assume that we have created a project called “JPA_Demo.” To add a database to the project, all one need do is to select “Window | Services” from the main NetBeans Menu. The Services Tab will appear.

Right-Click Add-Driver

To add a new driver to NetBeans, underneath that Services Tab, right click on the “Drivers” Entry. Select “New Driver.”

Adding a new driver will display the “New JDBC Driver” Dialog Box. Once shown, merely click on that “Add” Button, then browse to wherever your “Derby.jar” file is located. Click “Okay”, then give your driver a snappy name (for the purposes of this demo, I named the driver “dbTQFTD”.)

Note that, by selecting “derby.jar” over the familiar “derbyclient.jar”, we told the driver that we were going to use an embedded database. The java-name for the driver will reflect that (pun intended.)

Right-Click Add-Database

Databases can be used anywhere. Hence now that we have a driver, if there is no database elsewhere, then we need to create one. Another right-click - this time on the Database line underneath that Services Tab, will do the trick:

Since our local database does not already exist, note that we added a “;create = true” suffix. -Also note how the JDBC URL contains the path to a local folder. Next, but certainly not least, do not forget to press that Test Connection Button – Don't do anything else until you can connect to your database a few times here. ...

Lastly, for that last creation-step, simply accept the default APP Schema. Press Finish and all will be well.

Note that after a new database is used (test creation does not count!), that the location encoded in that URL is where the new database will be created. (Windows folks should note that the '/' used above will resolve to '\' on any Microsoft OS.) -Be sure to add that database location to your backup plans?

Creating Database Tables (optional)

If you – like us – are creating a database from-scratch, then you – like me – will want to create a few tables in that locus.

Under NetBeans, the moment we touch our driver, the first thing to get used to is using a “Master Password.” -Working much like a password-key-chain super password, that Master Password is simply another way NetBeans attempts to secure the set of passwords that we probably want the Driver(s) to remember for us. --If you normally like to leave things like mega-passwords blank (not a option in the release I am using), then use use something like “password.”

Ever Users & Ever Passwords

Come to that, always having a default user & password is absolutely a best practice. -When it comes to using Derby, having both a default database user-ID and password are very next things to get used to!

Indeed, when using Derby, please, please, please note that not having both a user and a password is evil. --Not only will such omissions cause problems with the present version of the JPA Tooling, but to date I have traced many a teach-time-failure to students not using some type of default user AND password token.

Again, if you are the type of geek who does not like to use passwords, then defaulting to a user-id that matches the password (or vice versa ;) is not too bad of an idea (e.g. “password”, “admin”, “foo”, or “noneya” readily come to mind.)

Creating columns in a table are easy enough to do. Above, notice that I am obviously creating a table to store our quotations. When stored next to the DAYEVENTS Table, you might well guess where my weekend-work on is heading for 2013 … ?

Generating Java Objects

Now for the fun part: Getting NetBeans to pour-forth the Java!

While, in the past, mapping our objects to a database was a weekend task in-itself, through the miracle of modern ORM Tooling, the process is minuteladen. -By switching back from the current Sources Tab to that original Projects Tab, we can begin to enjoy some of that Java-creation goodness under NetBeans.

By right-clicking on our Project name (JP_Demo), we can select that “New | Other” interface from that pop-up menu. As shown above, once selected we have several Persistence chores to choose from.

The Persistence Unit

The first order of business is to create a new “Persistence Unit.” Invariably saved in our Project under the META-INF folder as “persistence.xml”, the PU is what the tooling uses to access our database:

When first created, the PU will not have any Entity Classes to show us. -Fortunately, any classes we generate will be automatically added to the persistence.xml definition.


Having used things like MyBATIS reminds us of the large gaps there can be between our legacy schema, and our Java Objects. Indeed, while tools like Hibernate & Microsoft's Entity Frameworks have traditionally focused upon what we are interested in doing next (i.e. creating Java Objects from a database table), the clear trend amongst all ORM tooling is to allow our objects to pick-and-choose from the columns amongst all of our database tables.

Trend noted however, for 100% of what we most often want to do with our OWN data, generating code to exactly-match a table is cool enough to be moving on with. Keeping that in mind therefore, yet again we right-click on the project name to activate that “New | Other | Persistence” View. Rather than creating another PU this time, we now want choose “Entity Classes From Database:”

Once we have defined our PU, the IDE is able to look-up each and every table entry in our database. Enjoyable enough to ponder in it's own right (yes, there is a way to do that ;), all we need do is to select the tables & package we want to use to hold the generated code. After that, feel free to select any additional options you may want to play with, press the buttons, and vola!: Your Java Code is ready, sir... -Would you like a controller with that?

The Driver: Our Ultimate Application?

The last step in our quest for database 'Nerdrvana is to do something useful with our PU, Entities, & Controllers. --Sadly, there is no magic tool for that.

Yet given my problem domain however (managing quotes), there is a nice example we can share. Deceptively simple, the example will none-the-less surely be of value to many, on many-a last-mile journey.


The first thing we need to do is to create + manage an EntityManagerFactory:

public class NojControl {

private static final String PUNIT_NAME = "JPA_DemoPU";
private static EntityManagerFactory factory = null;

public static EntityManagerFactory GetFactory() {
if (factory == null) {
factory = Persistence.createEntityManagerFactory(PUNIT_NAME);
return factory;

While of questionable value in the embedded environment (i.e. we can ONLY have a SINGLE Session to an embedded Derby Database!), note that the PUNIT_NAME is not the name of the file – it is the name of our PU in that XML Definition.

Note also that if you have not *also* included the derby.jar as part of your official set of project libraries, then we should do that, too.

(i.e Right-click on JPA_Demo to select "Properties." -Then click on the "Compile" Tab in the Dialog. Press "Add JAR/Folder" to select the derby.jar from the same location as used beneath that "Sources" Tab (described previously).)


Now we can perhaps let the code speak for itself:

public class mainLoader {
public static void main(String... args) {
EntityManagerFactory factory = NojControl.GetFactory();
EntityManager em = factory.createEntityManager();

// STEP: Create an entity in the database

Quote1 zq = new Quote1();
zq.setId((int) new Date().getTime());
zq.setAuthor("Mr. Test");
zq.setQuote("To be, or the heck with it.");;


// STEP: Read existing entities & to console
Query q = em.createQuery("SELECT q FROM Quote1 q");
List<Quote1> qlist = q.getResultList();
for (Quote1 ref : qlist) {
System.out.println("Entries: " + qlist.size());


Give it a try?
[EL Info]: 2012-12-30 12:12:51.342--ServerSession(1477356634)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Info]: 2012-12-30 12:12:53.415--ServerSession(1477356634)--file:/d_drive/USR/code/java/Examples/JPA_Demo/build/classes/_JPA_DemoPU login successful
com.TheQuoteForToday.Quote1[ id=-322090977 ]
Entries: 1
BUILD SUCCESSFUL (total time: 4 seconds)

Notes & Techniques

There are two items worthy of further discussion: Grab Files, and Creation Strategies.

Grab Files

After creating any table, be sure to create a “grab” file. Why? Because when it comes time to re-create a table (be it in another database, or while recovering from some unforeseeable R&D mishap (not so uncommon when dealing with Derby!), one can quickly re-create, rather than create, a table.

Note that "Edit table script" Button in the above animation - very handy!

Creation Strategies

Akin to the above, also note that the PU has some extremely handy database / table re-creation options, as well:

Given that populating data from other technologies can be an iterative process, the above database management features allow us to have the option to start-the-database-over – or not – as required.

Live the Profession!


[ add comment ] ( 6756 views )   |  permalink  |  related link
Capital has been described as ... 

From the EBook of International Finance:

"... Capital has been described above as money put to certain purposes. This was done for the sake of clearness and because this definition fits in with the facts as they usually happen in these days. Economists define capital as wealth reserved for production, and we must always remember that money is only a claim for, or a right to, a certain amount of goods or a certain amount of other people's work. Money is only a title to wealth, because if I have a sovereign or a one-pound note in my pocket, I thereby have the power of buying a pound's worth of goods or of hiring a doctor to cure me or a parson to bury me or anybody else to do anything that I want, up to the buying power of that sovereign. This is the power that money carries with it. When the owner of this power, instead of exercising it in providing himself with luxuries or amusements, uses it by lending it to someone who wants to build a factory, and employ workers, then, because the owner of the money receives his rate of interest he is said to be exploiting labour, because, so it is alleged, the workers work and he, the capitalist, sits in idleness and lives on their labour.

And so, in fact, he does. But we have not yet found out how he got the money that he lent. That money can only have been got by work done or services rendered, for which other people were ready to pay. Capital, looked at from this point of view, is simply stored up work, and entitled to its reward just as much as the work done yesterday. The capitalist lives on the work of others, but he can only do so because he has wrought himself in days gone by or because someone else has wrought and handed on to him the fruits of his labour. ..."

Nice read - Here is the free eBook. Feel free to share this book by Mr. Hartley Withers with any eager learners you may bump into over the holidays?



[ add comment ] ( 3116 views )   |  permalink  |  related link

<<First <Back | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | Next> Last>>