Tuesday, July 25, 2006
Start with an XML schema and everything else just drops out?
In some ways it would be nice to think that what ever problem domain you're working in, you could start with some kind of XML schema and everything else would just drop out! To elaborate, what I mean is that if you're in the business of persisting XML, you could start with your schema and then have the code that creates and (optionally) validates the schema and then persists this all created for you automatically. Of course, if you're using a relational database backend, it will create the schema and write all the SQL for you too! Well, almost ;-). It's not that far off, but this post just captures the interventions we had to make in order for this to be (an otherwise) seamless end-to-end process!
JAXB Binding Stage
JAXB Binding Stage
- In the XML schema an
eventList
consists of a sequence ofevent
elements. The default JAXB binding is to model this asList<Event> getEvent()
; for the sake of correctness, we have a directive in thebinding.xjb
file to say that the corresponding property should be calledevents
, therefore we get the correct plural formList<Event> getEvents()
. - The schema for XML schema itself, has a plethora of types related to capturing dates and / or times (check out the full list here). We went for the
dateTime
type in our schema (which basically captures a date and time down to the millisecond with timezone offset). JAXB created a new class to model this in Java calledjavax.xml.datatype.XMLGregorianCalendar
. In Java it's more typical to handle a date time as ajava.util.Date
(or ajava.sql.Date
). For us it made sense for the JAXB object to model it as ajava.util.Date
as this is a type that all JDO implementations must be able to handle and model by default. However, this meant that we had to create an adapter class that can convert from a string inxs:dateTime
format to aDate
and another to perform the reverse. (Thankfully there are utility methods to help in this regard!). Then we add another directive in thebinding.xjb
file referring to this adapter class and an instruction to model this "property" as aDate
in the corresponding JAXB class.
- It has to be said that JAXB 2.0 models XML schema enumerations beautifully now; it's as natural and as obvious a mapping was one could imagine! However, not so JDO 2.0. Certainly, for this version of the specification they could not quite agree on how to do this formally! With JPOX what you have to do is first of all download a plugin jar
jpox-java5.jar
and make it available to the runtime. Secondly you can choose to model the corresponding Javaenum
as either a JDBCVARCHAR
or as anINT
. For clarity when viewing the database tables during development we choseVARCHAR
. This has to be added as a directive in thepackage.jdo
mapping file.