Database access from JavaFX Script

Given that there is a wealth of JDBC code out there, I suspect that many developers may try to leverage their investment as they build new rich internet applications with JavaFX. I'll be using NetBeans 6.5 to demonstrate a simple example.

We'll use a simple JavaFX script project, which generates hello world code. Use the libraries node in the project view to add the "Java DB Driver".

As you can see, I am calling TalkToJavaDB.getRecord() which returns a java.lang.String, which in turn I assign to the Text object in my JavaFX script. I am using the Java String object to store an index of the java.sql.ResultSet I get from connecting to a JavaDB (derby) that ships with either Java 6 or GlassFish (v2 in my case).

This example is very trivial and may improve it in time to iterate over the ResultSet and present the data in a more visually apealing way (after all JavaFX enables developers to build great user interfaces, in many cases in half the time and with a lot less code)

Comments:

You are aware that all JavaFX scripts run inside the Event Disptach Thread right? that means your sample application is accessing the database in the EDT, a big no-no.

Posted by Andres Almiray on January 19, 2009 at 04:52 AM PST #

Andres is correct that accessing the database on the event thread is something that can hinder application responsiveness.

JavaFX Script is primarily aimed at RIA-style applications. As such, most data-driven apps will likely get their data via a Web Services request rather than directly using JDBC, in which case you can use the existing web services APIs to move the blocking operation off the EDT. I think the point here was that it was quite easy to "mix and match" a JavaFX Script front-end with a Java back end.

The example could easily be extended to do the work off-thread, though. The front-end is calling a Java method to return the result. That Java method could enqueue the actual work onto an Executor which would run the JDBC request in another thread, whose last action would be to post an event back to FX (via Fx.deferTask()) which would store the result in an FX variable. Then instead of initializing
content: JavaClass.getRecord()

you'd initialize it with a bind:

content: bind recordHolder

When the data arrives from the background thread, the UI would be updated.

For web services requests, there's already a mechanism in place in the runtime libraries for hiding these mechanics; as the runtime libraries continue to evolve, fewer machinations will be required to move asynchronous or blocking activities off of the EDT in less standard cases like this one.

Posted by Brian Goetz on February 02, 2009 at 09:23 AM PST #

Post a Comment:
Comments are closed for this entry.
About

octav

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today