tags:

views:

559

answers:

3

The problem

Dynamically add and remove fields to entities on the fly using Hibernate.

I m sure this is a common scenario, most enterprise applications will require some level of customization. so what is the best way to do it? also ideally it should not require a recompile and smoothly create/remove the field in the schema and allow the application to continue working.

If its just a question of updating the xml, ( i m pretty sure the proxy classes are required) then how does the schema gets reloaded?

Thanks a million for input

Note: If you think there is a better solution I m also all ears thanks

A: 

I did this once (digging in my memory). Okay. Do this:

  • Download the source of Hibernate
  • look up the class which loads the XML config

You'll see that it creates a class which contains the table definitions. Note the field names and types involved. If the field is private, then Field.setAccessible(true) is your friend.

What you need to do is query the global config class for the list of tables, find your table and then modify the list of fields. The problem starts with mapping these fields to some class, because you can't change the Java class at runtime).

Since this is pretty complex, here is a more simple way: Create a Hibernate mapping with all fields and then use a custom query to load only a subset. You can easily create such a query at runtime using HQL. Specify only the columns you need and Hibernate won't try to load the rest.

Aaron Digulla
A: 

I don't think it's a very common use case and as Aaron suggests it's going to take you quite a while to nail this down.

The schema update will not be straightforward either. Even thought Hibernate does offer programmatic schema changes, it's limited to simple things like adding/removing fields. That might work for you, but if the data type or nullability of a column changes, Hibernate won't update it for you.

You may want to consider a OneToMany relationship and store the data as a row in a separate table, assuming you can accept the overhead of another join.

cliff.meyers
A: 

I was researching the same problem and found the following article: Using Hibernate to Support Custom Domain Object Fields