Site Sponsors:
New Project: SQLMate 
Well, here we code again ...

One might have noted that I am somewhat obsessed with SQLite at the moment ... and for good reason: From Android to Big Data, we are using SQLite on every 'conceivable.

So when it came time for me to mass-generate a few hundred tables & DAO's recently, I decided to write yet another source code generator.

See the related link (below) for a tad more information.


Cheers,

-Rn


[ add comment ] ( 320 views )   |  permalink  |  related link
Pay-As-You-Go -v- Global Initialization 
While easy to understand in Java, the opportunity to initialize data & classes prior to their use is a well known technique.

Here is a Java:


static ColorPair[] colors = null;

static {
List<ColorPair> array = new ArrayList<ColorPair>();
Color[] ccc = {
Color.BLACK,
Color.BLUE,
Color.CYAN,
Color.DARK_GRAY,
Color.GRAY,
Color.GREEN,
Color.LIGHT_GRAY,
Color.MAGENTA,
Color.ORANGE,
Color.PINK,
Color.RED,
Color.WHITE,
Color.YELLOW
};
for (Color a : ccc) {
for (Color b : ccc) {
if (a == b) {
continue;
}
array.add(new ColorPair(a, b));
}
}
colors = new ColorPair[array.size()];
array.toArray(colors);
}


Indeed, when we are guaranteed to use static content, then taking the time to pre-initialize objects is a common practice. Why would anyone want to do anything else?

Yet when calculating the total latency in pre-execution load times, on more than one occasion I have been found re-factoring static initializers so as to allow programs to be more responsive.

Pay As-You Go


Given that the above example has been defined as package-protected, surely it can be declared private.


private static ColorPair[] colors = null;


After so hiding the data structure, the very next thing to do might be to expose the structure with a more visible member function.


public static ColorPair[] GetDefaultColors() {
return colors;
}


Once so exposed, a far less costly initialization strategy can be created. -Specifically, rather than requiring colors to be pre-initialized, we can now pay-as-we-go by only allowing the initialization loop to run when the data are needed:


private static void init() {
List<ColorPair> array = new ArrayList<ColorPair>();
Color[] ccc = {
Color.BLACK,
Color.BLUE,
Color.CYAN,
Color.DARK_GRAY,
Color.GRAY,
Color.GREEN,
Color.LIGHT_GRAY,
Color.MAGENTA,
Color.ORANGE,
Color.PINK,
Color.RED,
Color.WHITE,
Color.YELLOW
};
for (Color a : ccc) {
for (Color b : ccc) {
if (a == b) {
continue;
}
array.add(new ColorPair(a, b));
}
}
colors = new ColorPair[array.size()];
array.toArray(colors);
}


Note in the above that the initialization still takes place as before, but not every time our program is loaded. Rather, we can "pay as we go" by allowing the structure to be initialized only if, as well as when, the data are required:


public static ColorPair[] GetDefaultColors() {
if(colors == null)
init();
return colors;
}


Conclusion


Whenever I find myself migrating a bit of code from a project into a support library the first thing I look for is an opportunity to convert any global / static initializers into a pay-as-you-go strategy. Of course, given that one of the first principles of good Object Oriented Design is Encapsulation, from a puritanical point of view many often find very little justification for doing anything else.

Enjoy the Journey!

-- Rn

[ add comment ] ( 422 views )   |  permalink
Database + Java + NetBeans = Cooler-er 
It is Sunday … time to take a moment & share a few techniques!

Focus


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 TheQuoteForToday.com 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.

Table-to-Java


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.

EntityManagerFactory


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).)

main


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
em.getTransaction().begin();

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

em.getTransaction().commit();

// 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(ref);
}
System.out.println("Entries: " + qlist.size());

em.close();
}
}

Give it a try?
run:
[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!

-Rn




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

| 1 | 2 | 3 | 4 | Next> Last>>