Share this page to your:
Mastodon

Say you have an existing database. You access it with JDBC and you maintain it with SQL scripts.

Life is hard because you have to coordinate changes to the SQL with changes to the Java. This is why Hibernate and similar tools were invented. There are tools which will look at an existing database and build the right entity classes so you to can use JPA.

My experience with those tools has not been very good. But once you have the entity classes you can say those classes are the ‘master’ definitions of the database objects. You don’t maintain SQL anymore, you generate it from those entity classes. You get all kinds of advantages with this which the Hibernate people can tell you about.

But you can go a step further. Say you decide that you would really like all your entity classes to have the @Cache annotation added. Say you want them all to have a specific toString() method. If you are using the entity classes as master you have a lot of editing to do.

Using an XSD file along with HyperJAXB3 to generate your entity classes means the XSD is now the master. For the @Cache and toString() cases you can just change the generation options and rerun the generation. This is very easy. You have a lot of other options around injecting standard code into your entities that you did not have before. Some of them (like toString()) may require you to write a JAXB plugin but most, like the @Cache, do not. This is because there are a lot of useful plugins already out there such as Annox and Madura Objects.

But you still have a problem. How do you get from your SQL database to your XSD file without writing it all by hand?

That’s where you use schema-builder. It scans your database using JDBC and generates the XSD file you want. It figures out the OneToMany and manyToOne relationships based on the foreign keys you’ve set up already.
There are some restrictions:

  • Not all JDBC data types are supported, though the most common ones are.
  • ManyToMany relationships are not handled
  • We don’t handle multi field keys.
  • Inherititance relationships are not detected.

To get around the last three just generate the XSD and edit it. You should regard the generated XSD as almost correct but which needs tidying around those three points. To add more data types needs code changes, not hard but there are a lot of obscure data types and I just added the common ones.

Previous Post Next Post