views:

1944

answers:

3

IDEs like Netbeans allow generation of entity classes through a persistence context. If you had access to underlying generation method (not sure if it is an external tool or part of the IDE), could you generate database entity classes dynamically at runtime? The idea being that you could hook into the entity classes using reflection.

I know you can go the other way and generate the database from the entity class, however due to permissions issues in my work environment that would be a no go. However, if you reverse the process and pull the classes from the database it may be feasible in my environment. The idea being that the database would serve as a single point of configuration/control.

A: 

It's theoretically possible but what would be the point? Java is statically typed so you would only be able to use the generated classes by reflection and you would have no way of giving them behaviour, so removing the whole point of object-relational mapping. Loading the data into Maps or just using SQL record sets would be more convenient.

If you have an existing schema you can write classes that act in the way your application needs and declaratively map them onto the schema. That way the code is the simplest expression of your application logic and is persistence-agnostic.

Nat
I actually took the map approach already in another application. I wanted to experiment with doing this through an ORM layer. The primary idea is to allow the database to be the primary point of configuration and then have the program react dynamically to that. This is more of an academic purist then a practical one. I've already written an application that works, now I want to see if I can improve on it.
James McMahon
I don't think this is the best way to improve it. Why not first try to use JPA the way it is designed to be used. Write clean, persistence-agnostic object-oriented code and use JPA to map your classes onto your database schema. That would be both "pure" and "practical".
Nat
Nat, I've also done that before. Like I said, this is more about experimenting with something new.
James McMahon
A: 

You can find on JBoss website a tool to do the reverse engineering from database to java objects.

The source code is available, you should dig in!

https://www.jboss.org/tools/download/stable.html

Valentin Jacquemin
Is Jboss the standard tool for this? It seems like a lot of IDEs have this capability, so I assumed there must be a standard JPA or Hibernate tool that builds ORM classes from the DB.
James McMahon
Standard I don't know. This is the one used by Hibernate anyway
Valentin Jacquemin
Sadly this looks like Hibernate only.
James McMahon
A: 

Assuming you're using Hibernate, you might be able to use Hibernate Tools to generate the database schema. Although primarily designed for Eclipse and Ant, its theoretically possible to link it in and invoke it like any other JAR.

Steve Kuo
Thanks, don't suppose you know a JPA equivalent?
James McMahon